jenkins-bot has submitted this change. (
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1164610?usp=email )
Change subject: IMPR: Remove unnecessary assignment before return statement
......................................................................
IMPR: Remove unnecessary assignment before return statement
Change-Id: I378812aeefc10d60def34c30dfe7d0542391a346
---
M pywikibot/_wbtypes.py
M pywikibot/comms/http.py
M pywikibot/cosmetic_changes.py
M pywikibot/diff.py
M pywikibot/page/_links.py
M pywikibot/pagegenerators/_generators.py
M pywikibot/proofreadpage.py
M pywikibot/site/_datasite.py
M pywikibot/site/_generators.py
M pywikibot/textlib.py
M pywikibot/time.py
M pywikibot/xmlreader.py
M scripts/category_graph.py
M scripts/create_isbn_edition.py
M scripts/noreferences.py
M scripts/nowcommons.py
M scripts/transwikiimport.py
M tests/link_tests.py
M tests/logentries_tests.py
M tests/memento_tests.py
M tests/script_tests.py
21 files changed, 103 insertions(+), 131 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/_wbtypes.py b/pywikibot/_wbtypes.py
index e39e1b4..8ca7557 100644
--- a/pywikibot/_wbtypes.py
+++ b/pywikibot/_wbtypes.py
@@ -1,6 +1,6 @@
"""Wikibase data type classes."""
#
-# (C) Pywikibot team, 2013-2024
+# (C) Pywikibot team, 2013-2025
#
# Distributed under the terms of the MIT license.
#
@@ -778,14 +778,14 @@
:return: Wikibase JSON
"""
- json = {'time': self.toTimestr(),
- 'precision': self.precision,
- 'after': self.after,
- 'before': self.before,
- 'timezone': self.timezone,
- 'calendarmodel': self.calendarmodel
- }
- return json
+ return {
+ 'time': self.toTimestr(),
+ 'precision': self.precision,
+ 'after': self.after,
+ 'before': self.before,
+ 'timezone': self.timezone,
+ 'calendarmodel': self.calendarmodel,
+ }
@classmethod
def fromWikibase(cls, data: dict[str, Any],
@@ -908,12 +908,12 @@
:return: Wikibase JSON
"""
- json = {'amount': self._fromdecimal(self.amount),
- 'upperBound': self._fromdecimal(self.upperBound),
- 'lowerBound': self._fromdecimal(self.lowerBound),
- 'unit': self.unit
- }
- return json
+ return {
+ 'amount': self._fromdecimal(self.amount),
+ 'upperBound': self._fromdecimal(self.upperBound),
+ 'lowerBound': self._fromdecimal(self.lowerBound),
+ 'unit': self.unit,
+ }
@classmethod
def fromWikibase(cls, data: dict[str, Any],
@@ -956,10 +956,10 @@
:return: Wikibase JSON
"""
- json = {'text': self.text,
- 'language': self.language
- }
- return json
+ return {
+ 'text': self.text,
+ 'language': self.language,
+ }
@classmethod
def fromWikibase(cls, data: dict[str, Any],
@@ -1109,12 +1109,11 @@
:param site: The Wikibase site
"""
- specifics = {
+ return {
'ending': '.map',
'label': 'geo-shape',
- 'data_site': cls._get_data_site(site)
+ 'data_site': cls._get_data_site(site),
}
- return specifics
class WbTabularData(WbDataPage):
@@ -1135,12 +1134,11 @@
:param site: The Wikibase site
"""
- specifics = {
+ return {
'ending': '.tab',
'label': 'tabular-data',
- 'data_site': cls._get_data_site(site)
+ 'data_site': cls._get_data_site(site),
}
- return specifics
class WbUnknown(WbRepresentation):
diff --git a/pywikibot/comms/http.py b/pywikibot/comms/http.py
index ef9802a..f6d4bc0 100644
--- a/pywikibot/comms/http.py
+++ b/pywikibot/comms/http.py
@@ -237,11 +237,10 @@
values['script_comments'] = '; '.join(script_comments)
format_string = format_string or config.user_agent_format
-
formatted = _USER_AGENT_FORMATTER.format(format_string, **values)
+
# clean up after any blank components
- formatted = formatted.replace('()', '').replace(' ', ' ').strip()
- return formatted
+ return formatted.replace('()', '').replace(' ', ' ').strip()
def fake_user_agent() -> str:
@@ -576,7 +575,5 @@
' in the response header.'
)
- _encoding = _try_decode(response.content, header_encoding) \
+ return _try_decode(response.content, header_encoding) \
or _try_decode(response.content, charset)
-
- return _encoding
diff --git a/pywikibot/cosmetic_changes.py b/pywikibot/cosmetic_changes.py
index c128860..55ea751 100644
--- a/pywikibot/cosmetic_changes.py
+++ b/pywikibot/cosmetic_changes.py
@@ -673,10 +673,9 @@
r'(\|(?P<label>[^\]\|]*))?\]\](?P<linktrail>'
+ self.site.linktrail() + ')')
- text = textlib.replaceExcept(text, linkR, handleOneLink,
+ return textlib.replaceExcept(text, linkR, handleOneLink,
['comment', 'math', 'nowiki', 'pre',
'startspace'])
- return text
def resolveHtmlEntities(self, text: str) -> str:
"""Replace HTML entities with string."""
@@ -702,9 +701,8 @@
ignore.append(58) # Colon (:)
# TODO: T254350 - what other extension tags should be avoided?
# (graph, math, score, timeline, etc.)
- text = pywikibot.html2unicode(
+ return pywikibot.html2unicode(
text, ignore=ignore, exceptions=['comment', 'syntaxhighlight'])
- return text
def removeEmptySections(self, text: str) -> str:
"""Cleanup empty sections."""
@@ -759,9 +757,9 @@
'startspace', 'table']
if self.site.sitename != 'wikipedia:cs':
exceptions.append('template')
- text = textlib.replaceExcept(text, r'(?m)[\t ]+( |$)', r'\1',
+
+ return textlib.replaceExcept(text, r'(?m)[\t ]+( |$)', r'\1',
exceptions, site=self.site)
- return text
def removeNonBreakingSpaceBeforePercent(self, text: str) -> str:
"""Remove a non-breaking space between number and percent sign.
@@ -770,9 +768,8 @@
space in front of a percent sign, so it is no longer required to
place it manually.
"""
- text = textlib.replaceExcept(
+ return textlib.replaceExcept(
text, r'(\d)&(?:nbsp|#160|#x[Aa]0);%', r'\1 %', ['timeline'])
- return text
def cleanUpSectionHeaders(self, text: str) -> str:
"""Add a space between the equal signs and the section title.
@@ -917,12 +914,13 @@
# this will cause mistakes.
extensions = [fr'\.{ext}'
for ext in ['pdf', 'html?', 'php', 'aspx?', 'jsp']]
- text = textlib.replaceExcept(
+
+ return textlib.replaceExcept(
text,
r'\[(?P<url>https?://[^\|\] ]+?(' + '|'.join(extensions) + r')) *'
r'\| *(?P<label>[^\|\]]+?)\]',
- r'[\g<url> \g<label>]', exceptions)
- return text
+ r'[\g<url> \g<label>]', exceptions
+ )
def fixHtml(self, text: str) -> str:
"""Replace html markups with wikitext markups."""
diff --git a/pywikibot/diff.py b/pywikibot/diff.py
index e142a4d..052e934 100644
--- a/pywikibot/diff.py
+++ b/pywikibot/diff.py
@@ -166,8 +166,7 @@
if line_ref is None:
if color in self.colors:
- colored_line = f'<<{self.colors[color]}>>{line}<<default>>'
- return colored_line
+ return f'<<{self.colors[color]}>>{line}<<default>>'
return line
colored_line = ''
diff --git a/pywikibot/page/_links.py b/pywikibot/page/_links.py
index 67657bb..639cd30 100644
--- a/pywikibot/page/_links.py
+++ b/pywikibot/page/_links.py
@@ -736,12 +736,11 @@
:return: Wikibase JSON
"""
- json = {
+ return {
'site': self._sitekey,
'title': self._rawtitle,
'badges': [badge.title() for badge in self.badges]
}
- return json
# Utility functions for parsing page titles
diff --git a/pywikibot/pagegenerators/_generators.py
b/pywikibot/pagegenerators/_generators.py
index a6c60b5..4e04b8c 100644
--- a/pywikibot/pagegenerators/_generators.py
+++ b/pywikibot/pagegenerators/_generators.py
@@ -1478,15 +1478,13 @@
:return: Dictionary of querystring parameters to use in the
query
"""
- query = {
+ return {
'id': id,
'action': 'get_data',
'format': 'json',
'doit': ''
}
- return query
-
def query(self) -> Generator[str, None, None]:
"""Query PagePile.
diff --git a/pywikibot/proofreadpage.py b/pywikibot/proofreadpage.py
index 2e55202..024dd8b 100644
--- a/pywikibot/proofreadpage.py
+++ b/pywikibot/proofreadpage.py
@@ -10,7 +10,7 @@
.. seealso:: https://wikisource.org/wiki/Wikisource:Google_OCR
"""
#
-# (C) Pywikibot team, 2015-2024
+# (C) Pywikibot team, 2015-2025
#
# Distributed under the terms of the MIT license.
#
@@ -303,9 +303,8 @@
@classmethod
def get_descriptors(cls):
"""Get TagAttrDesc descriptors."""
- res = {k: v for k, v in cls.__dict__.items()
- if isinstance(v, TagAttrDesc)}
- return res
+ return {k: v for k, v in cls.__dict__.items()
+ if isinstance(v, TagAttrDesc)}
def __contains__(self, attr) -> bool:
return getattr(self, attr) is not None
diff --git a/pywikibot/site/_datasite.py b/pywikibot/site/_datasite.py
index 92f9693..d67f2ba 100644
--- a/pywikibot/site/_datasite.py
+++ b/pywikibot/site/_datasite.py
@@ -1,6 +1,6 @@
"""Objects representing API interface to Wikibase site."""
#
-# (C) Pywikibot team, 2012-2024
+# (C) Pywikibot team, 2012-2025
#
# Distributed under the terms of the MIT license.
#
@@ -827,11 +827,10 @@
del kwargs['site']
parameters = dict(search=search, language=language, **kwargs)
- gen = self._generator(api.APIGenerator,
- type_arg='wbsearchentities',
- data_name='search',
- total=total, parameters=parameters)
- return gen
+ return self._generator(api.APIGenerator,
+ type_arg='wbsearchentities',
+ data_name='search',
+ total=total, parameters=parameters)
def parsevalue(self, datatype: str, values: list[str],
options: dict[str, Any] | None = None,
diff --git a/pywikibot/site/_generators.py b/pywikibot/site/_generators.py
index 7d8534c..bf76ec7 100644
--- a/pywikibot/site/_generators.py
+++ b/pywikibot/site/_generators.py
@@ -1608,11 +1608,11 @@
sort = 'none'
if sort != 'relevance':
parameters['gsrsort'] = sort
- srgen = self._generator(api.PageGenerator, type_arg='search',
- namespaces=namespaces,
- total=total, g_content=content,
- parameters=parameters)
- return srgen
+
+ return self._generator(api.PageGenerator, type_arg='search',
+ namespaces=namespaces,
+ total=total, g_content=content,
+ parameters=parameters)
def usercontribs(
self,
@@ -1892,10 +1892,10 @@
"""
usprop = ['blockinfo', 'gender', 'groups', 'editcount', 'registration',
'rights', 'emailable']
- usgen = api.ListGenerator(
- 'users', site=self, parameters={
- 'ususers': usernames, 'usprop': usprop})
- return usgen
+ return api.ListGenerator(
+ 'users', site=self,
+ parameters={'ususers': usernames, 'usprop': usprop}
+ )
def randompages(
self,
diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py
index 257e1a7..039bc25 100644
--- a/pywikibot/textlib.py
+++ b/pywikibot/textlib.py
@@ -211,8 +211,7 @@
r'((({{{[^{}]+?}}}|{{[^{}]+?}}|{[^{}]*?})[^{]*?)*?)?'
r'|)\s*}}'
) % {'namespace': ':|'.join(namespaces), 'pattern': pattern}
- templateRegex = re.compile(templateRegexP, flags)
- return templateRegex
+ return re.compile(templateRegexP, flags)
def search_any_predicate(self, templates):
"""Return a predicate that matches any template."""
diff --git a/pywikibot/time.py b/pywikibot/time.py
index 62bd7b4..2e6832b 100644
--- a/pywikibot/time.py
+++ b/pywikibot/time.py
@@ -3,7 +3,7 @@
.. versionadded:: 7.5
"""
#
-# (C) Pywikibot team, 2007-2024
+# (C) Pywikibot team, 2007-2025
#
# Distributed under the terms of the MIT license.
#
@@ -197,9 +197,8 @@
sec -= 1
usec = 1_000_000 - usec
- ts = cls(1970, 1, 1) + datetime.timedelta(seconds=sec,
- microseconds=usec)
- return ts
+ return cls(1970, 1, 1) + datetime.timedelta(seconds=sec,
+ microseconds=usec)
@classmethod
def _from_string(cls, timestr: str) -> Timestamp:
diff --git a/pywikibot/xmlreader.py b/pywikibot/xmlreader.py
index a1994cf..47f04b8 100644
--- a/pywikibot/xmlreader.py
+++ b/pywikibot/xmlreader.py
@@ -11,7 +11,7 @@
vulnerable XML attacks. *defusedxml* 0.7.1 or higher is recommended.
"""
#
-# (C) Pywikibot team, 2005-2024
+# (C) Pywikibot team, 2005-2025
#
# Distributed under the terms of the MIT license.
#
@@ -290,7 +290,7 @@
elem.findtext(f'{uri}restrictions')
)
- headers = Headers(
+ return Headers(
title=elem.findtext(f'{uri}title'),
ns=elem.findtext(f'{uri}ns'),
pageid=elem.findtext(f'{uri}id'),
@@ -299,8 +299,6 @@
move_restriction=move_restriction,
)
- return headers
-
def _create_revision(
self, headers: Headers, revision: Element
) -> XmlEntry:
@@ -311,7 +309,7 @@
username = ip_editor or contributor.findtext(f'{uri}username')
username = username or '' # username might be deleted
- xml_entry = XmlEntry(
+ return XmlEntry(
title=headers.title,
ns=headers.ns,
id=headers.pageid,
@@ -327,8 +325,6 @@
# could get comment, minor as well
)
- return xml_entry
-
wrapper = ModuleDeprecationWrapper(__name__)
wrapper.add_deprecated_attr(
diff --git a/scripts/category_graph.py b/scripts/category_graph.py
index 65c6206..0a8f8ab 100755
--- a/scripts/category_graph.py
+++ b/scripts/category_graph.py
@@ -43,7 +43,7 @@
.. versionadded:: 8.0
"""
#
-# (C) Pywikibot team, 2022-2024
+# (C) Pywikibot team, 2022-2025
#
# Distributed under the terms of the MIT license.
#
@@ -126,28 +126,26 @@
def node():
subs = ', '.join([c.title(with_ns=False).replace(' ', ' ')
for c in subcats])
- n = pydot.Node(title,
- label=rf'"{title}\n{len(subcats)} C"',
- tooltip=title + '\n\n' + subs,
- URL=cat.full_url(),
- fontsize=int(10 * size))
- return n
+ return pydot.Node(title,
+ label=f'"{title}\n{len(subcats)} C"',
+ tooltip=f'{title}\n\n{subs}',
+ URL=cat.full_url(),
+ fontsize=int(10 * size))
def edge(n, h):
minlen = n % columns + 1 if level != self.args.depth else 1
- e = pydot.Edge(title,
- subcat.title(with_ns=False),
- tooltip=title + ' ⟶ '
- + subcat.title(with_ns=False),
- headlabel=title,
- # distribute the graph to depth
- minlen=minlen,
- penwidth=round(size / 2, 2),
- arrowsize=round(size / 4, 2),
- color=str(round(h, 2)) + ' 1 0.7',
- labelfontsize=int(3 * size),
- labelfontcolor=str(round(h, 2)) + ' 1 0.5')
- return e
+ return pydot.Edge(title,
+ subcat.title(with_ns=False),
+ tooltip=title + ' ⟶ '
+ + subcat.title(with_ns=False),
+ headlabel=title,
+ # distribute the graph to depth
+ minlen=minlen,
+ penwidth=round(size / 2, 2),
+ arrowsize=round(size / 4, 2),
+ color=str(round(h, 2)) + ' 1 0.7',
+ labelfontsize=int(3 * size),
+ labelfontcolor=str(round(h, 2)) + ' 1 0.5')
if config.verbose_output:
pywikibot.info('Adding ' + cat.title(with_ns=False))
diff --git a/scripts/create_isbn_edition.py b/scripts/create_isbn_edition.py
index 1386492..c435a54 100755
--- a/scripts/create_isbn_edition.py
+++ b/scripts/create_isbn_edition.py
@@ -764,8 +764,7 @@
baselabel = baselabel.replace(',', ' ') # Remove remaining ","
# Remove redundant spaces
- baselabel = ' '.join(baselabel.split())
- return baselabel
+ return ' '.join(baselabel.split())
def get_item_list(item_name: str,
diff --git a/scripts/noreferences.py b/scripts/noreferences.py
index c251d64..bf4945b 100755
--- a/scripts/noreferences.py
+++ b/scripts/noreferences.py
@@ -670,12 +670,12 @@
templates_or_comments = re.compile(
r'^((?:\s*(?:\{\{[^\{\}]*?\}\}|<!--.*?-->))*)',
flags=re.DOTALL)
- new_text = (
+ return (
oldText[:match.end() - 1]
+ templates_or_comments.sub(
fr'\1\n{self.referencesText}\n',
- oldText[match.end() - 1:]))
- return new_text
+ oldText[match.end() - 1:])
+ )
else:
break
diff --git a/scripts/nowcommons.py b/scripts/nowcommons.py
index 6abfbeb..cab5ff4 100755
--- a/scripts/nowcommons.py
+++ b/scripts/nowcommons.py
@@ -265,6 +265,7 @@
else:
file_on_commons = val[1].strip()
return file_on_commons
+ return None
def init_page(self, item: pywikibot.Page) -> pywikibot.FilePage:
"""Ensure that generator retrieves FilePage objects."""
diff --git a/scripts/transwikiimport.py b/scripts/transwikiimport.py
index fe07d7d..d3932ef 100755
--- a/scripts/transwikiimport.py
+++ b/scripts/transwikiimport.py
@@ -156,8 +156,7 @@
def api_query(site, params: dict[str, str]):
"""Request data from given site."""
query = api.Request(site, parameters=params)
- datas = query.submit()
- return datas
+ return query.submit()
def main(*args: str) -> None:
diff --git a/tests/link_tests.py b/tests/link_tests.py
index bf04390..8b8a001 100755
--- a/tests/link_tests.py
+++ b/tests/link_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Test Link functionality."""
#
-# (C) Pywikibot team, 2014-2024
+# (C) Pywikibot team, 2014-2025
#
# Distributed under the terms of the MIT license.
#
@@ -123,30 +123,25 @@
"""Test that invalid titles raise InvalidTitleError."""
# Bad characters forbidden regardless of wgLegalTitleChars
def generate_contains_illegal_chars_exc_regex(text):
- exc_regex = (rf'^(u|)\'{re.escape(text)}\' contains illegal char'
- rf'\(s\) (u|)\'{re.escape(text[2])}\'$')
- return exc_regex
+ return (rf'^(u|)\'{re.escape(text)}\' contains illegal char'
+ rf'\(s\) (u|)\'{re.escape(text[2])}\'$')
# Directory navigation
def generate_contains_dot_combinations_exc_regex(text):
- exc_regex = (rf'^\(contains \. / combinations\): (u|)'
- rf'\'{re.escape(text)}\'$')
- return exc_regex
+ return (rf'^\(contains \. / combinations\): (u|)'
+ rf'\'{re.escape(text)}\'$')
# Tilde
def generate_contains_tilde_exc_regex(text):
- exc_regex = rf'^\(contains ~~~\): (u|)\'{re.escape(text)}\'$'
- return exc_regex
+ return rf'^\(contains ~~~\): (u|)\'{re.escape(text)}\'$'
# Overlength
def generate_overlength_exc_regex(text):
- exc_regex = rf'^\(over 255 bytes\): (u|)\'{re.escape(text)}\'$'
- return exc_regex
+ return rf'^\(over 255 bytes\): (u|)\'{re.escape(text)}\'$'
# Namespace prefix without actual title
def generate_has_no_title_exc_regex(text):
- exc_regex = rf'^(u|)\'{re.escape(text.strip())}\' has no title\.$'
- return exc_regex
+ return rf'^(u|)\'{re.escape(text.strip())}\' has no title\.$'
title_tests = [
# Empty title
diff --git a/tests/logentries_tests.py b/tests/logentries_tests.py
index 3fafb13..9b4447e 100755
--- a/tests/logentries_tests.py
+++ b/tests/logentries_tests.py
@@ -68,8 +68,7 @@
with skipping(StopIteration,
msg=f'No entry found for {logtype!r}'):
- le = next(self.site.logevents(logtype=logtype, total=1))
- return le
+ return next(self.site.logevents(logtype=logtype, total=1))
def _test_logevent(self, logtype) -> None:
"""Test a single logtype entry."""
diff --git a/tests/memento_tests.py b/tests/memento_tests.py
index 1e37fde..8647906 100755
--- a/tests/memento_tests.py
+++ b/tests/memento_tests.py
@@ -34,8 +34,7 @@
if date_string else None)
with skipping(ReadTimeout, RequestsConnectionError,
MementoClientException):
- result = get_closest_memento_url(url, when, self.timegate_uri)
- return result
+ return get_closest_memento_url(url, when, self.timegate_uri)
class TestMementoArchive(MementoTestCase):
diff --git a/tests/script_tests.py b/tests/script_tests.py
index 4926930..19e4eed 100755
--- a/tests/script_tests.py
+++ b/tests/script_tests.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Test that each script can be compiled and executed."""
#
-# (C) Pywikibot team, 2014-2024
+# (C) Pywikibot team, 2014-2025
#
# Distributed under the terms of the MIT license.
#
@@ -53,11 +53,12 @@
def list_scripts(path, exclude=None):
"""Return list of scripts in given path."""
- scripts = [name[0:-3] for name in os.listdir(path) # strip '.py'
- if name.endswith('.py')
- and not name.startswith('_') # skip __init__.py and _*
- and name != exclude]
- return scripts
+ return [
+ name[0:-3] for name in os.listdir(path) # strip '.py'
+ if name.endswith('.py')
+ and not name.startswith('_') # skip __init__.py and _*
+ and name != exclude
+ ]
script_list = framework_scripts + list_scripts(scripts_path)
--
To view, visit
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1164610?usp=email
To unsubscribe, or for help writing mail filters, visit
https://gerrit.wikimedia.org/r/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I378812aeefc10d60def34c30dfe7d0542391a346
Gerrit-Change-Number: 1164610
Gerrit-PatchSet: 1
Gerrit-Owner: Xqt <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
_______________________________________________
Pywikibot-commits mailing list -- [email protected]
To unsubscribe send an email to [email protected]