jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/871237 )
Change subject: Make some string operations robust and verbose ......................................................................
Make some string operations robust and verbose
Use removeprefix/removesuffix where they correspond to the intent.
Change-Id: Ia1323e0f02c30ae3b55874cb41029346ef925639 --- M pywikibot/__init__.py M pywikibot/data/sparql.py M pywikibot/family.py M tests/family_tests.py M scripts/category_redirect.py M tests/gui_tests.py M pywikibot/pagegenerators/_factory.py M pywikibot/scripts/preload_sites.py M pywikibot/i18n.py M pywikibot/site_detect.py M scripts/claimit.py M pywikibot/data/api/_paraminfo.py M pywikibot/config.py M tests/__init__.py 14 files changed, 45 insertions(+), 24 deletions(-)
Approvals: Xqt: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py index 9202523..f49d581 100644 --- a/pywikibot/__init__.py +++ b/pywikibot/__init__.py @@ -691,7 +691,7 @@
# also allow entity URIs to be provided via unit parameter if isinstance(unit, str) \ - and unit.partition('://')[0] not in ('http', 'https'): + and not unit.startswith(('http://', 'https://')): raise ValueError("'unit' must be an ItemPage or entity uri.")
if error is None and not self._require_errors(site): diff --git a/pywikibot/config.py b/pywikibot/config.py index 1746a02..66248b3 100644 --- a/pywikibot/config.py +++ b/pywikibot/config.py @@ -62,6 +62,7 @@ List, Mapping, Tuple, + removeprefix, removesuffix, ) from pywikibot.logging import error, output, warning @@ -338,7 +339,7 @@ base_dir = '' for arg in sys.argv[1:]: if arg.startswith('-dir:'): - base_dir = arg[5:] + base_dir = removeprefix(arg, '-dir:') base_dir = os.path.expanduser(base_dir) break else: diff --git a/pywikibot/data/api/_paraminfo.py b/pywikibot/data/api/_paraminfo.py index 87422f4..f3accae 100644 --- a/pywikibot/data/api/_paraminfo.py +++ b/pywikibot/data/api/_paraminfo.py @@ -243,7 +243,8 @@ params['modules'] = [mod for mod in module_batch if not mod.startswith('query+') and mod not in self.root_modules] - params['querymodules'] = [mod[6:] for mod in module_batch + params['querymodules'] = [removeprefix(mod, 'query+') + for mod in module_batch if mod.startswith('query+')]
for mod in set(module_batch) & self.root_modules: diff --git a/pywikibot/data/sparql.py b/pywikibot/data/sparql.py index 0f0dcc0..1b3fcc4 100644 --- a/pywikibot/data/sparql.py +++ b/pywikibot/data/sparql.py @@ -11,7 +11,7 @@ from requests.exceptions import Timeout
from pywikibot import Site, config, sleep, warning -from pywikibot.backports import Dict, List +from pywikibot.backports import Dict, List, removeprefix from pywikibot.comms import http from pywikibot.exceptions import Error, TimeoutError
@@ -227,9 +227,8 @@
:return: ID of Wikibase object, e.g. Q1234 """ - urllen = len(self.entity_url) if self.value.startswith(self.entity_url): - return self.value[urllen:] + return removeprefix(self.value, self.entity_url) return None
def __repr__(self) -> str: diff --git a/pywikibot/family.py b/pywikibot/family.py index dff749a..87519ca 100644 --- a/pywikibot/family.py +++ b/pywikibot/family.py @@ -19,7 +19,13 @@
import pywikibot from pywikibot import config -from pywikibot.backports import Dict, List, Set, Tuple # skipcq: PY-W2000 +from pywikibot.backports import ( # skipcq: PY-W2000 + Dict, + List, + Set, + Tuple, + removesuffix, +) from pywikibot.exceptions import FamilyMaintenanceWarning, UnknownFamilyError from pywikibot.tools import classproperty, deprecated, remove_last_args
@@ -1035,7 +1041,7 @@ def scriptpath(self, code): """Extract the script path from the URL.""" if self.url.path.endswith('/api.php'): - return self.url.path[0:-8] + return removesuffix(self.url.path, '/api.php')
# AutoFamily refers to the variable set below, not the function # but the reference must be given here diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py index 9a19dac..a18fa8a 100644 --- a/pywikibot/i18n.py +++ b/pywikibot/i18n.py @@ -41,6 +41,7 @@ Match, Sequence, cache, + removesuffix, ) from pywikibot.plural import plural_rule
@@ -810,7 +811,7 @@ pathname = os.path.join(next(iter(mod.__path__)), package)
# build a list of languages in that directory - langs = [filename.partition('.')[0] + langs = [removesuffix(filename, '.json') for filename in sorted(os.listdir(pathname)) if filename.endswith('.json')]
diff --git a/pywikibot/pagegenerators/_factory.py b/pywikibot/pagegenerators/_factory.py index f32c8e3..d965d26 100644 --- a/pywikibot/pagegenerators/_factory.py +++ b/pywikibot/pagegenerators/_factory.py @@ -23,6 +23,7 @@ List, Sequence, Tuple, + removeprefix, ) from pywikibot.bot import ShowingListOption from pywikibot.data import api @@ -622,7 +623,7 @@ value = pywikibot.input('What namespace are you filtering on?') not_key = 'not:' if value.startswith(not_key): - value = value[len(not_key):] + value = removeprefix(value, not_key) resolve = self.site.namespaces.resolve not_ns = set(resolve(value.split(','))) if not self._namespaces: diff --git a/pywikibot/scripts/preload_sites.py b/pywikibot/scripts/preload_sites.py index 6273279..533f739 100755 --- a/pywikibot/scripts/preload_sites.py +++ b/pywikibot/scripts/preload_sites.py @@ -28,7 +28,7 @@ from typing import Optional, Union
import pywikibot -from pywikibot.backports import List, Set +from pywikibot.backports import List, Set, removeprefix from pywikibot.family import Family
@@ -100,6 +100,6 @@ for arg in pywikibot.handle_args(): if arg in families_list: fam.add(arg) - elif arg.startswith('-worker'): - worker = int(arg.partition(':')[2]) + elif arg.startswith('-worker:'): + worker = int(removeprefix(arg, '-worker:')) preload_families(fam or families_list, worker) diff --git a/pywikibot/site_detect.py b/pywikibot/site_detect.py index b4b2f6b..45f269d 100644 --- a/pywikibot/site_detect.py +++ b/pywikibot/site_detect.py @@ -16,6 +16,7 @@
import pywikibot from pywikibot.comms.http import fetch +from pywikibot.backports import removesuffix from pywikibot.exceptions import ServerError from pywikibot.tools import MediaWikiVersion
@@ -45,8 +46,7 @@ :raises Timeout: a timeout occurred while loading the site :raises RuntimeError: Version not found or version less than 1.27 """ - if fromurl.endswith('$1'): - fromurl = fromurl[:-2] + fromurl = removesuffix(fromurl, '$1')
r = fetch(fromurl, **kwargs) check_response(r) diff --git a/scripts/category_redirect.py b/scripts/category_redirect.py index fd90c6f..532116a 100755 --- a/scripts/category_redirect.py +++ b/scripts/category_redirect.py @@ -42,7 +42,7 @@
import pywikibot from pywikibot import config, i18n, pagegenerators -from pywikibot.backports import Tuple +from pywikibot.backports import Tuple, removeprefix from pywikibot.bot import ConfigParserBot, SingleSiteBot from pywikibot.exceptions import CircularRedirectError, Error, NoPageError
@@ -495,8 +495,7 @@ options = {} for arg in pywikibot.handle_args(args): if arg.startswith('-delay:'): - pos = arg.find(':') - options[arg[1:pos]] = int(arg[pos + 1:]) + options['delay'] = int(removeprefix(arg, '-delay:')) else: # generic handling of we have boolean options options[arg[1:]] = True diff --git a/scripts/claimit.py b/scripts/claimit.py index cfffe99..ac4f9e6 100755 --- a/scripts/claimit.py +++ b/scripts/claimit.py @@ -52,6 +52,7 @@ # import pywikibot from pywikibot import WikidataBot, pagegenerators +from pywikibot.backports import removeprefix from pywikibot.tools.itertools import itergroup
@@ -114,7 +115,7 @@ for arg in local_args: # Handle args specifying how to handle duplicate claims if arg.startswith('-exists:'): - exists_arg = arg.split(':')[1] + exists_arg = removeprefix(arg, '-exists:') continue # Handle page generator args if gen.handle_arg(arg): diff --git a/tests/__init__.py b/tests/__init__.py index c4b9b3c..a06d063 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -27,7 +27,7 @@
import pywikibot.data.api from pywikibot import config -from pywikibot.backports import Dict, List +from pywikibot.backports import Dict, List, removesuffix from pywikibot.data.api import CachedRequest from pywikibot.data.api import Request as _original_Request from pywikibot.tools import PYTHON_VERSION @@ -176,7 +176,7 @@ def _unknown_test_modules(): """List tests which are to be executed.""" dir_list = os.listdir(join_tests_path()) - all_test_set = {name[0:-9] for name in dir_list # strip '_tests.py' + all_test_set = {removesuffix(name, '_tests.py') for name in dir_list if name.endswith('_tests.py') and not name.startswith('_')} # skip __init__.py and _*
diff --git a/tests/family_tests.py b/tests/family_tests.py index b8b1f33..a1d649c 100755 --- a/tests/family_tests.py +++ b/tests/family_tests.py @@ -36,7 +36,7 @@ self.assertTrue(iter(f.domains)) for domain in f.domains: self.assertIsInstance(domain, str) - if domain.split(':', 1)[0] != 'localhost': + if not domain.startswith('localhost:'): self.assertIn('.', domain)
self.assertEqual(f.name, name) diff --git a/tests/gui_tests.py b/tests/gui_tests.py index 5439738..a908542 100755 --- a/tests/gui_tests.py +++ b/tests/gui_tests.py @@ -22,8 +22,8 @@ def test_tk_dialog(self): """Test Tk dialog.""" desc = 'foo' - image = 'tests/data/images/MP_sounds.png' - filename = image.rsplit('/', 1)[1] + filename = 'MP_sounds.png' + image = f'tests/data/images/{filename}' box = Tkdialog(desc, image, filename) # skip after ~100 ms box.root.after(100, box.skip_file)