summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFlorian Bruhin <me@the-compiler.org>2024-10-13 15:28:44 +0200
committerFlorian Bruhin <me@the-compiler.org>2024-10-13 18:24:44 +0200
commit4d069b8fc3f482fb0308391e453d7d69523de753 (patch)
tree9e38eac0696f7034f853caf536241ee034f57d66
parentfe868901aba6efcc28fe903fd20cfe278e4c838d (diff)
downloadqutebrowser-4d069b8fc3f482fb0308391e453d7d69523de753.tar.gz
qutebrowser-4d069b8fc3f482fb0308391e453d7d69523de753.zip
Use str.removeprefix() and str.removesuffix()
https://docs.python.org/3/whatsnew/3.9.html#new-string-methods-to-remove-prefixes-and-suffixes
-rw-r--r--qutebrowser/browser/network/pac.py2
-rw-r--r--qutebrowser/browser/webengine/darkmode.py2
-rw-r--r--qutebrowser/completion/completer.py2
-rw-r--r--qutebrowser/config/qtargs.py4
-rw-r--r--qutebrowser/misc/keyhintwidget.py2
-rw-r--r--qutebrowser/utils/error.py4
-rw-r--r--qutebrowser/utils/urlmatch.py2
-rw-r--r--qutebrowser/utils/urlutils.py6
-rw-r--r--scripts/dev/check_coverage.py2
-rw-r--r--scripts/dev/pylint_checkers/qute_pylint/config.py2
-rw-r--r--scripts/dev/recompile_requirements.py8
-rwxr-xr-xscripts/dev/update_3rdparty.py3
-rw-r--r--tests/end2end/features/conftest.py20
-rw-r--r--tests/end2end/test_dirbrowser.py2
-rw-r--r--tests/end2end/test_invocations.py2
-rw-r--r--tests/unit/browser/webengine/test_webview.py4
-rw-r--r--tests/unit/javascript/test_js_quirks.py4
-rw-r--r--tests/unit/keyinput/test_keyutils.py4
-rw-r--r--tests/unit/misc/test_editor.py2
19 files changed, 38 insertions, 39 deletions
diff --git a/qutebrowser/browser/network/pac.py b/qutebrowser/browser/network/pac.py
index 656c620db..20516366e 100644
--- a/qutebrowser/browser/network/pac.py
+++ b/qutebrowser/browser/network/pac.py
@@ -242,7 +242,7 @@ class PACFetcher(QObject):
pac_prefix = "pac+"
assert url.scheme().startswith(pac_prefix)
- url.setScheme(url.scheme()[len(pac_prefix):])
+ url.setScheme(url.scheme().removeprefix(pac_prefix))
self._pac_url = url
with qtlog.disable_qt_msghandler():
diff --git a/qutebrowser/browser/webengine/darkmode.py b/qutebrowser/browser/webengine/darkmode.py
index 8f1908547..5aab28051 100644
--- a/qutebrowser/browser/webengine/darkmode.py
+++ b/qutebrowser/browser/webengine/darkmode.py
@@ -418,7 +418,7 @@ def settings(
blink_settings_flag = f'--{_BLINK_SETTINGS}='
for flag in special_flags:
if flag.startswith(blink_settings_flag):
- for pair in flag[len(blink_settings_flag):].split(','):
+ for pair in flag.removeprefix(blink_settings_flag).split(','):
key, val = pair.split('=', maxsplit=1)
result[_BLINK_SETTINGS].append((key, val))
diff --git a/qutebrowser/completion/completer.py b/qutebrowser/completion/completer.py
index 846fa7c22..408660c3a 100644
--- a/qutebrowser/completion/completer.py
+++ b/qutebrowser/completion/completer.py
@@ -127,7 +127,7 @@ class Completer(QObject):
Return:
([parts_before_cursor], 'part_under_cursor', [parts_after_cursor])
"""
- text = self._cmd.text()[len(self._cmd.prefix()):]
+ text = self._cmd.text().removeprefix(self._cmd.prefix())
if not text or not text.strip():
# Only ":", empty part under the cursor with nothing before/after
return [], '', []
diff --git a/qutebrowser/config/qtargs.py b/qutebrowser/config/qtargs.py
index 3a648524e..eb5e8b58c 100644
--- a/qutebrowser/config/qtargs.py
+++ b/qutebrowser/config/qtargs.py
@@ -91,10 +91,10 @@ def _qtwebengine_features(
for flag in special_flags:
if flag.startswith(_ENABLE_FEATURES):
- flag = flag[len(_ENABLE_FEATURES):]
+ flag = flag.removeprefix(_ENABLE_FEATURES)
enabled_features += flag.split(',')
elif flag.startswith(_DISABLE_FEATURES):
- flag = flag[len(_DISABLE_FEATURES):]
+ flag = flag.removeprefix(_DISABLE_FEATURES)
disabled_features += flag.split(',')
elif flag.startswith(_BLINK_SETTINGS):
pass
diff --git a/qutebrowser/misc/keyhintwidget.py b/qutebrowser/misc/keyhintwidget.py
index 32867c17a..5662763b8 100644
--- a/qutebrowser/misc/keyhintwidget.py
+++ b/qutebrowser/misc/keyhintwidget.py
@@ -123,7 +123,7 @@ class KeyHintView(QLabel):
).format(
html.escape(prefix),
suffix_color,
- html.escape(str(seq)[len(prefix):]),
+ html.escape(str(seq).removeprefix(prefix)),
html.escape(cmd)
)
text = '<table>{}</table>'.format(text)
diff --git a/qutebrowser/utils/error.py b/qutebrowser/utils/error.py
index 010970861..10dad90f7 100644
--- a/qutebrowser/utils/error.py
+++ b/qutebrowser/utils/error.py
@@ -11,11 +11,11 @@ from qutebrowser.utils import log, utils
def _get_name(exc: BaseException) -> str:
"""Get a suitable exception name as a string."""
- prefixes = ['qutebrowser', 'builtins']
+ prefixes = ['qutebrowser.', 'builtins.']
name = utils.qualname(exc.__class__)
for prefix in prefixes:
if name.startswith(prefix):
- name = name[len(prefix) + 1:]
+ name = name.removeprefix(prefix)
break
return name
diff --git a/qutebrowser/utils/urlmatch.py b/qutebrowser/utils/urlmatch.py
index 55b0037dc..0d3f76cb8 100644
--- a/qutebrowser/utils/urlmatch.py
+++ b/qutebrowser/utils/urlmatch.py
@@ -128,7 +128,7 @@ class UrlPattern:
# FIXME This doesn't actually strip the hostname correctly.
if (pattern.startswith('file://') and
not pattern.startswith('file:///')):
- pattern = 'file:///' + pattern[len("file://"):]
+ pattern = 'file:///' + pattern.removeprefix("file://")
return pattern
diff --git a/qutebrowser/utils/urlutils.py b/qutebrowser/utils/urlutils.py
index 6f0e910cf..785569069 100644
--- a/qutebrowser/utils/urlutils.py
+++ b/qutebrowser/utils/urlutils.py
@@ -553,8 +553,8 @@ def same_domain(url1: QUrl, url2: QUrl) -> bool:
if suffix1 != suffix2:
return False
- domain1 = url1.host()[:-len(suffix1)].split('.')[-1]
- domain2 = url2.host()[:-len(suffix2)].split('.')[-1]
+ domain1 = url1.host().removesuffix(suffix1).split('.')[-1]
+ domain2 = url2.host().removesuffix(suffix2).split('.')[-1]
return domain1 == domain2
@@ -668,7 +668,7 @@ def parse_javascript_url(url: QUrl) -> str:
urlstr = url.toString(FormatOption.ENCODED)
urlstr = urllib.parse.unquote(urlstr)
- code = urlstr[len('javascript:'):]
+ code = urlstr.removeprefix('javascript:')
if not code:
raise Error("Resulted in empty JavaScript code")
diff --git a/scripts/dev/check_coverage.py b/scripts/dev/check_coverage.py
index e1d0d8642..6de04703f 100644
--- a/scripts/dev/check_coverage.py
+++ b/scripts/dev/check_coverage.py
@@ -242,7 +242,7 @@ def _get_filename(filename):
os.path.join(os.path.dirname(__file__), '..', '..'))
common_path = os.path.commonprefix([basedir, filename])
if common_path:
- filename = filename[len(common_path):].lstrip('/')
+ filename = filename.removeprefix(common_path).lstrip('/')
return filename
diff --git a/scripts/dev/pylint_checkers/qute_pylint/config.py b/scripts/dev/pylint_checkers/qute_pylint/config.py
index be5bae082..6effc8836 100644
--- a/scripts/dev/pylint_checkers/qute_pylint/config.py
+++ b/scripts/dev/pylint_checkers/qute_pylint/config.py
@@ -50,7 +50,7 @@ class ConfigChecker(checkers.BaseChecker):
node_str = node.as_string()
prefix = 'config.val.'
if node_str.startswith(prefix):
- self._check_config(node, node_str[len(prefix):])
+ self._check_config(node, node_str.removeprefix(prefix))
def _check_config(self, node, name):
"""Check that we're accessing proper config options."""
diff --git a/scripts/dev/recompile_requirements.py b/scripts/dev/recompile_requirements.py
index 838e75931..5c0622141 100644
--- a/scripts/dev/recompile_requirements.py
+++ b/scripts/dev/recompile_requirements.py
@@ -114,7 +114,7 @@ def get_all_names():
"""Get all requirement names based on filenames."""
for filename in glob.glob(os.path.join(REQ_DIR, 'requirements-*.txt-raw')):
basename = os.path.basename(filename)
- yield basename[len('requirements-'):-len('.txt-raw')]
+ yield basename.removeprefix('requirements-').removesuffix('.txt-raw')
def run_pip(venv_dir, *args, quiet=False, **kwargs):
@@ -231,7 +231,7 @@ def extract_requirement_name(path: pathlib.Path) -> str:
prefix = "requirements-"
assert path.suffix == ".txt", path
assert path.stem.startswith(prefix), path
- return path.stem[len(prefix):]
+ return path.stem.removeprefix(prefix)
def parse_versioned_line(line):
@@ -274,11 +274,11 @@ def _get_changes(diff):
continue
elif line.startswith('--- '):
prefix = '--- a/'
- current_path = pathlib.Path(line[len(prefix):])
+ current_path = pathlib.Path(line.removeprefix(prefix))
continue
elif line.startswith('+++ '):
prefix = '+++ b/'
- new_path = pathlib.Path(line[len(prefix):])
+ new_path = pathlib.Path(line.removeprefix(prefix))
assert current_path == new_path, (current_path, new_path)
continue
elif not line.strip():
diff --git a/scripts/dev/update_3rdparty.py b/scripts/dev/update_3rdparty.py
index 4d8a5e562..1258be106 100755
--- a/scripts/dev/update_3rdparty.py
+++ b/scripts/dev/update_3rdparty.py
@@ -104,8 +104,7 @@ def update_pdfjs(target_version=None, legacy=False, gh_token=None):
else:
# We need target_version as x.y.z, without the 'v' prefix, though the
# user might give it on the command line
- if target_version.startswith('v'):
- target_version = target_version[1:]
+ target_version = target_version.removeprefix('v')
# version should have the prefix to be consistent with the return value
# of get_latest_pdfjs_url()
version = 'v' + target_version
diff --git a/tests/end2end/features/conftest.py b/tests/end2end/features/conftest.py
index b7f112182..22fde0001 100644
--- a/tests/end2end/features/conftest.py
+++ b/tests/end2end/features/conftest.py
@@ -216,22 +216,22 @@ def open_path(quteproc, server, path):
while True:
if path.endswith(new_tab_suffix):
- path = path[:-len(new_tab_suffix)]
+ path = path.removesuffix(new_tab_suffix)
new_tab = True
elif path.endswith(new_bg_tab_suffix):
- path = path[:-len(new_bg_tab_suffix)]
+ path = path.removesuffix(new_bg_tab_suffix)
new_bg_tab = True
elif path.endswith(new_window_suffix):
- path = path[:-len(new_window_suffix)]
+ path = path.removesuffix(new_window_suffix)
new_window = True
elif path.endswith(private_suffix):
- path = path[:-len(private_suffix)]
+ path = path.removesuffix(private_suffix)
private = True
elif path.endswith(as_url_suffix):
- path = path[:-len(as_url_suffix)]
+ path = path.removesuffix(as_url_suffix)
as_url = True
elif path.endswith(do_not_wait_suffix):
- path = path[:-len(do_not_wait_suffix)]
+ path = path.removesuffix(do_not_wait_suffix)
wait = False
else:
break
@@ -264,7 +264,7 @@ def run_command(quteproc, server, tmpdir, command):
invalid_tag = ' (invalid command)'
if command.endswith(invalid_tag):
- command = command[:-len(invalid_tag)]
+ command = command.removesuffix(invalid_tag)
invalid = True
else:
invalid = False
@@ -639,11 +639,11 @@ def check_open_tabs(quteproc, request, tabs):
while line.endswith(active_suffix) or line.endswith(pinned_suffix):
if line.endswith(active_suffix):
# active
- line = line[:-len(active_suffix)]
+ line = line.removesuffix(active_suffix)
active = True
else:
# pinned
- line = line[:-len(pinned_suffix)]
+ line = line.removesuffix(pinned_suffix)
pinned = True
session_tab = session['windows'][0]['tabs'][i]
@@ -739,7 +739,7 @@ def set_up_fileselector(quteproc, py_proc, tmpdir, kind, files, output_type):
tmp_file = None
for i, arg in enumerate(sys.argv):
if arg.startswith('--file='):
- tmp_file = arg[len('--file='):]
+ tmp_file = arg.removeprefix('--file=')
sys.argv.pop(i)
break
selected_files = sys.argv[1:]
diff --git a/tests/end2end/test_dirbrowser.py b/tests/end2end/test_dirbrowser.py
index 58cf66d6a..b2e3a8e29 100644
--- a/tests/end2end/test_dirbrowser.py
+++ b/tests/end2end/test_dirbrowser.py
@@ -124,7 +124,7 @@ def parse(quteproc):
title_prefix = 'Browse directory: '
# Strip off the title prefix to obtain the path of the folder that
# we're browsing
- path = pathlib.Path(soup.title.string[len(title_prefix):])
+ path = pathlib.Path(soup.title.string.removeprefix(title_prefix))
container = soup('div', id='dirbrowserContainer')[0]
diff --git a/tests/end2end/test_invocations.py b/tests/end2end/test_invocations.py
index db6fd2eec..5f65041c7 100644
--- a/tests/end2end/test_invocations.py
+++ b/tests/end2end/test_invocations.py
@@ -988,7 +988,7 @@ def test_restart(request, quteproc_new):
quteproc_new.wait_for_quit()
assert line.message.startswith(prefix)
- pid = int(line.message[len(prefix):])
+ pid = int(line.message.removeprefix(prefix))
os.kill(pid, signal.SIGTERM)
try:
diff --git a/tests/unit/browser/webengine/test_webview.py b/tests/unit/browser/webengine/test_webview.py
index f14a896b6..8ffc81d60 100644
--- a/tests/unit/browser/webengine/test_webview.py
+++ b/tests/unit/browser/webengine/test_webview.py
@@ -25,10 +25,10 @@ class Naming:
def camel_to_snake(naming, name):
if naming.prefix:
assert name.startswith(naming.prefix)
- name = name[len(naming.prefix):]
+ name = name.removeprefix(naming.prefix)
if naming.suffix:
assert name.endswith(naming.suffix)
- name = name[:-len(naming.suffix)]
+ name = name.removesuffix(naming.suffix)
# https://stackoverflow.com/a/1176023
return re.sub(r'(?<!^)(?=[A-Z])', '_', name).lower()
diff --git a/tests/unit/javascript/test_js_quirks.py b/tests/unit/javascript/test_js_quirks.py
index 9218c6d0d..981f9d9e8 100644
--- a/tests/unit/javascript/test_js_quirks.py
+++ b/tests/unit/javascript/test_js_quirks.py
@@ -55,7 +55,7 @@ def test_js_quirks(config_stub, js_tester_webengine, base_url, source, expected)
def test_js_quirks_match_files(webengine_tab):
quirks_path = pathlib.Path(qutebrowser.__file__).parent / "javascript" / "quirks"
suffix = ".user.js"
- quirks_files = {p.name[:-len(suffix)] for p in quirks_path.glob(f"*{suffix}")}
+ quirks_files = {p.name.removesuffix(suffix) for p in quirks_path.glob(f"*{suffix}")}
quirks_code = {q.filename for q in webengine_tab._scripts._get_quirks()}
assert quirks_code == quirks_files
@@ -66,7 +66,7 @@ def test_js_quirks_match_settings(webengine_tab, configdata_init):
valid_values = opt.typ.get_valid_values()
assert valid_values is not None
quirks_config = {
- val[len(prefix):].replace("-", "_")
+ val.removeprefix(prefix).replace("-", "_")
for val in valid_values
if val.startswith(prefix)
}
diff --git a/tests/unit/keyinput/test_keyutils.py b/tests/unit/keyinput/test_keyutils.py
index 572456a22..257bd89a2 100644
--- a/tests/unit/keyinput/test_keyutils.py
+++ b/tests/unit/keyinput/test_keyutils.py
@@ -57,7 +57,7 @@ def qtest_key(request):
def test_key_data_keys():
"""Make sure all possible keys are in key_data.KEYS."""
- key_names = {name[len("Key_"):]
+ key_names = {name.removeprefix("Key_")
for name in testutils.enum_members(Qt, Qt.Key)}
key_data_names = {key.attribute for key in sorted(key_data.KEYS)}
diff = key_names - key_data_names
@@ -66,7 +66,7 @@ def test_key_data_keys():
def test_key_data_modifiers():
"""Make sure all possible modifiers are in key_data.MODIFIERS."""
- mod_names = {name[:-len("Modifier")]
+ mod_names = {name.removesuffix("Modifier")
for name, value in testutils.enum_members(Qt, Qt.KeyboardModifier).items()
if value not in [Qt.KeyboardModifier.NoModifier, Qt.KeyboardModifier.KeyboardModifierMask]}
mod_data_names = {mod.attribute for mod in sorted(key_data.MODIFIERS)}
diff --git a/tests/unit/misc/test_editor.py b/tests/unit/misc/test_editor.py
index 3f7edd143..debfa7b9e 100644
--- a/tests/unit/misc/test_editor.py
+++ b/tests/unit/misc/test_editor.py
@@ -163,7 +163,7 @@ class TestFileHandling:
msg = message_mock.getmsg(usertypes.MessageLevel.info)
prefix = 'Editor backup at '
assert msg.text.startswith(prefix)
- fname = msg.text[len(prefix):]
+ fname = msg.text.removeprefix(prefix)
with qtbot.wait_signal(editor.editing_finished):
editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit)