Skip to content

Commit

Permalink
Use removeprefix/suffix string methods
Browse files Browse the repository at this point in the history
These were added in Python 3.9
  • Loading branch information
johannaengland committed Aug 7, 2024
1 parent 0a90566 commit a917a22
Show file tree
Hide file tree
Showing 17 changed files with 26 additions and 42 deletions.
4 changes: 1 addition & 3 deletions python/nav/alertengine/dispatchers/sms_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,4 @@ def get_fallback_message(self, alert, language, message_type):

@staticmethod
def is_valid_address(address):
if address.startswith("+"):
return address[1:].isdigit()
return address.isdigit()
return address.removeprefix("+").isdigit()
2 changes: 1 addition & 1 deletion python/nav/bin/navmain.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def _service_printer(service):

kind = service.__class__.__name__
if kind.endswith("Service"):
kind = kind[:-7].lower()
kind = kind.removesuffix("Service").lower()
kind = "({})".format(kind)
kind = "{:>8}".format(kind)
colors.print_color(kind, colors.COLOR_YELLOW, newline=False)
Expand Down
3 changes: 1 addition & 2 deletions python/nav/django/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@

def is_valid_point_string(point_string):
if len(point_string.split(',')) == 2:
if point_string.startswith('(') and point_string.endswith(')'):
point_string = point_string[1:-1]
point_string = point_string.removeprefix("(").removesuffix(")")
x_point, y_point = point_string.split(',')
try:
Decimal(x_point.strip())
Expand Down
2 changes: 1 addition & 1 deletion python/nav/ipdevpoll/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def __init__(self, name, interval, intensity, plugins, description=''):
def from_config_section(cls, config, section):
"""Creates a JobDescriptor from a ConfigParser section"""
if section.startswith(JOB_PREFIX):
jobname = section[len(JOB_PREFIX) :]
jobname = section.removeprefix(JOB_PREFIX)
else:
raise InvalidJobSectionName(section)

Expand Down
6 changes: 1 addition & 5 deletions python/nav/ipdevpoll/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __init__(self, pidlog=False):
def format(self, record):
"""Overridden to choose format based on record contents."""
self._set_context(record)
self._strip_logger_prefix(record)
record.name = record.name.removeprefix(self.prefix)
return Formatter.format(self, record)

def _set_context(self, record):
Expand All @@ -64,10 +64,6 @@ def _set_format(self, fmt):
self._fmt = fmt
self._style._fmt = fmt

def _strip_logger_prefix(self, record):
if record.name.startswith(self.prefix):
record.name = record.name[len(self.prefix) :]


# pylint: disable=R0903
class ContextLogger(object):
Expand Down
3 changes: 1 addition & 2 deletions python/nav/ipdevpoll/plugins/dot1q.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,7 @@ def _get_vlan_names(self):
for vlannum, name in names.items():
vlannum = self._remap_vlan(vlannum)
suffix = '+{}'.format(vlannum)
if name.endswith(suffix):
name = name[: -len(suffix)]
name = name.removesuffix(suffix)
vlan = self.containers.factory(name, shadows.Vlan)
vlan.net_type = shadows.NetType.get('lan')
vlan.vlan = vlannum
Expand Down
2 changes: 1 addition & 1 deletion python/nav/ipdevpoll/plugins/prefix.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ def __init__(self, string):
for oper in self.OPERATORS:
if string.startswith(oper):
self.match_operator = oper
string = string[len(oper) :]
string = string.removeprefix(oper)
break

IP.__init__(self, string) # stupid old-style class implementation!
Expand Down
12 changes: 4 additions & 8 deletions python/nav/models/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,10 @@ def from_db_value(self, value, expression, connection):
def to_python(self, value):
if not value or isinstance(value, tuple):
return value
if isinstance(value, str):
if validators.is_valid_point_string(value):
if value.startswith('(') and value.endswith(')'):
noparens = value[1:-1]
else:
noparens = value
latitude, longitude = noparens.split(',')
return (Decimal(latitude.strip()), Decimal(longitude.strip()))
if isinstance(value, str) and validators.is_valid_point_string(value):
noparens = value.removeprefix("(").removesuffix(")")
latitude, longitude = noparens.split(',')
return (Decimal(latitude.strip()), Decimal(longitude.strip()))
raise exceptions.ValidationError("This value must be a point-string.")

def get_db_prep_value(self, value, connection, prepared=False):
Expand Down
9 changes: 3 additions & 6 deletions python/nav/models/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,12 +509,9 @@ def get_short_sysname(self):
"""Returns sysname without the domain suffix if specified in the
DOMAIN_SUFFIX setting in nav.conf"""

if settings.DOMAIN_SUFFIX is not None and self.sysname.endswith(
settings.DOMAIN_SUFFIX
):
return self.sysname[: -len(settings.DOMAIN_SUFFIX)]
else:
return self.sysname or self.ip
if settings.DOMAIN_SUFFIX is not None:
return self.sysname.removesuffix(settings.DOMAIN_SUFFIX)
return self.sysname or self.ip

def is_on_maintenance(self):
"""Returns True if this netbox is currently on maintenance"""
Expand Down
6 changes: 3 additions & 3 deletions python/nav/models/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,9 +282,9 @@ def locked(self):

@locked.setter
def locked(self, value):
if not value and self.password.startswith('!'):
self.password = self.password[1:]
elif value and not self.password.startswith('!'):
if not value:
self.password = self.password.removeprefix("!")
elif not self.password.startswith('!'):
self.password = '!' + self.password

@property
Expand Down
2 changes: 1 addition & 1 deletion python/nav/startstop.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def get_info_from_content(content):
if not line.startswith('#'):
break
elif line.startswith(INFOHEAD):
return line[len(INFOHEAD) :].strip()
return line.removeprefix(INFOHEAD).strip()


class Service(object):
Expand Down
3 changes: 1 addition & 2 deletions python/nav/statemon/abstractchecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,7 @@ def get_type(cls):
"""Returns the name of the handler."""
suffix = "checker"
name = cls.__name__.lower()
if name.endswith(suffix):
name = name[: -len(suffix)]
name = name.removesuffix(suffix)
return name

def get_address(self):
Expand Down
2 changes: 1 addition & 1 deletion python/nav/statemon/checker/FtpChecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def execute(self):
version = ''
for line in welcome.split('\n'):
if line.startswith('220 '):
version = line[4:].strip()
version = line.removeprefix('220 ').strip()
self.version = version

username = self.args.get('username', '')
Expand Down
2 changes: 1 addition & 1 deletion python/nav/statemon/checker/MysqlChecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def read_packet(self):

data = self.file.read(size)
if data.startswith(b'\xff'):
error = data[3:].decode("utf-8")
error = data.removeprefix(b'\xff').decode("utf-8")
raise MysqlError(error)

return data
Expand Down
2 changes: 1 addition & 1 deletion python/nav/statemon/checkermap.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,6 @@ def parsedir():
fnames = os.listdir(CHECKER_DIR)
for fname in fnames:
if fname.endswith(HANDLER_PATTERN):
key = fname[: -len(HANDLER_PATTERN)].lower()
key = fname.removesuffix(HANDLER_PATTERN).lower()
handler = fname[:-3]
register(key, handler)
5 changes: 2 additions & 3 deletions python/nav/web/geomap/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,9 +367,8 @@ def get_data(db_cursor, bounds, time_interval=None):
for netbox in netboxes:
netbox['load'] = float('nan')
netbox['real_sysname'] = netbox['sysname']
if _domain_suffix and netbox['sysname'].endswith(_domain_suffix):
hostname_length = len(netbox['sysname']) - len(_domain_suffix)
netbox['sysname'] = netbox['sysname'][0:hostname_length]
if _domain_suffix:
netbox['sysname'] = netbox['sysname'].removesuffix(_domain_suffix)

return netboxes, connections

Expand Down
3 changes: 2 additions & 1 deletion tests/integration/models/model_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Intended purpose is to catch obvious omissions in DB state or the Django models
themselves.
"""

import os

from django.db import connection
Expand All @@ -21,7 +22,7 @@
# Ensure that all modules are loaded
for file_name in os.listdir(os.path.dirname(nav.models.__file__)):
if file_name.endswith('.py') and not file_name.startswith('__init__'):
module_name = file_name.replace('.py', '')
module_name = file_name.removesuffix('.py')
__import__('nav.models.%s' % module_name)


Expand Down

0 comments on commit a917a22

Please sign in to comment.