jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750782 )
Change subject: [fix] Fix some deepsource issues
......................................................................
[fix] Fix some deepsource issues
https://deepsource.io/gh/xqt/pwb/issues?category=all&analyzer=all&page=1
Change-Id: I2a57f0f726d69c526af2b296e5a3b4856b9499d5
---
M pywikibot/config.py
M pywikibot/data/api.py
M pywikibot/data/sparql.py
M pywikibot/site/_generators.py
M pywikibot/site/_siteinfo.py
M pywikibot/throttle.py
M pywikibot/userinterfaces/win32_unicode.py
M scripts/interwiki.py
M scripts/nowcommons.py
M scripts/patrol.py
M scripts/redirect.py
11 files changed, 121 insertions(+), 102 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/config.py b/pywikibot/config.py
index 259520a..09c185f 100644
--- a/pywikibot/config.py
+++ b/pywikibot/config.py
@@ -29,7 +29,7 @@
config2 was renamed to config
"""
#
-# (C) Pywikibot team, 2003-2021
+# (C) Pywikibot team, 2003-2022
#
# Distributed under the terms of the MIT license.
#
@@ -1130,23 +1130,24 @@
_all = False
else:
warning('Unknown arg {} ignored'.format(_arg))
+
for _name in sorted(globals().keys()):
- if _name[0] != '_':
- if not type(globals()[_name]) in [types.FunctionType,
- types.ModuleType]:
- if _all or _name in _modified:
- _value = globals()[_name]
- if _name in _private_values and _value:
- if isinstance(_value, dict):
- _value = '{ ...xxxxxxxx... }'
- elif hasattr(_value, '__dict__'):
- _value = (_value.__class__.__name__
- + '( ...xxxxxxxx... )')
- else:
- _value = repr('xxxxxxxx')
- else:
- _value = repr(_value)
- output('{}={}'.format(_name, _value))
+ if _name[0] != '_' \
+ and not type(globals()[_name]) in [types.FunctionType,
+ types.ModuleType] \
+ and (_all or _name in _modified):
+ _value = globals()[_name]
+
+ if _name not in _private_values or not _value:
+ _value = repr(_value)
+ elif isinstance(_value, dict):
+ _value = '{ ...xxxxxxxx... }'
+ elif hasattr(_value, '__dict__'):
+ _value = (_value.__class__.__name__
+ + '( ...xxxxxxxx... )')
+ else:
+ _value = repr('xxxxxxxx')
+ output('{}={}'.format(_name, _value))
# cleanup all locally-defined variables
for __var in list(globals().keys()):
diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index eaad672..87148d5 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -1,6 +1,6 @@
"""Interface to Mediawiki's api.php."""
#
-# (C) Pywikibot team, 2007-2021
+# (C) Pywikibot team, 2007-2022
#
# Distributed under the terms of the MIT license.
#
@@ -1233,10 +1233,10 @@
uiprop = self._params.get('uiprop', [])
uiprop = set(uiprop + ['blockinfo', 'hasmsg'])
self['uiprop'] = sorted(uiprop)
- if 'prop' in self._params:
- if self.site.has_extension('ProofreadPage'):
- prop = set(self['prop'] + ['proofread'])
- self['prop'] = sorted(prop)
+ if 'prop' in self._params \
+ and self.site.has_extension('ProofreadPage'):
+ prop = set(self['prop'] + ['proofread'])
+ self['prop'] = sorted(prop)
# When neither 'continue' nor 'rawcontinue' is present and the
# version number is at least 1.25wmf5 we add a dummy rawcontinue
# parameter. Querying siteinfo is save as it adds 'continue'
@@ -2548,9 +2548,9 @@
"""Extract results from resultdata."""
for item in resultdata:
result = self.result(item)
- if self._namespaces:
- if not self._check_result_namespace(result):
- continue
+ if self._namespaces and not self._check_result_namespace(result):
+ continue
+
yield result
if isinstance(item, dict) \
and set(self.continuekey) & set(item.keys()):
@@ -2884,13 +2884,13 @@
takes care of all the cookie stuff. Throws exception on failure.
"""
self.below_mw_1_27 = False
- if hasattr(self, '_waituntil'):
- if datetime.datetime.now() < self._waituntil:
- diff = self._waituntil - datetime.datetime.now()
- pywikibot.warning(
- 'Too many tries, waiting {} seconds before retrying.'
- .format(diff.seconds))
- pywikibot.sleep(diff.seconds)
+ if hasattr(self, '_waituntil') \
+ and datetime.datetime.now() < self._waituntil:
+ diff = self._waituntil - datetime.datetime.now()
+ pywikibot.warning(
+ 'Too many tries, waiting {} seconds before retrying.'
+ .format(diff.seconds))
+ pywikibot.sleep(diff.seconds)
self.site._loginstatus = LoginStatus.IN_PROGRESS
@@ -3017,11 +3017,10 @@
page._pageid = 0 # Non-existent page
else:
# Something is wrong.
- if page.site.sametitle(page.title(), pagedict['title']):
- if 'invalid' in pagedict:
- raise InvalidTitleError('{}: {}'
- .format(page,
- pagedict['invalidreason']))
+ if page.site.sametitle(page.title(), pagedict['title']) \
+ and 'invalid' in pagedict:
+ raise InvalidTitleError('{}: {}'
+ .format(page, pagedict['invalidreason']))
if int(pagedict['ns']) < 0:
raise UnsupportedPageError(page)
raise RuntimeError(
diff --git a/pywikibot/data/sparql.py b/pywikibot/data/sparql.py
index 416fb0d..f4b1899 100644
--- a/pywikibot/data/sparql.py
+++ b/pywikibot/data/sparql.py
@@ -1,6 +1,6 @@
"""SPARQL Query interface."""
#
-# (C) Pywikibot team, 2016-2020
+# (C) Pywikibot team, 2016-2022
#
# Distributed under the terms of the MIT license.
#
@@ -11,6 +11,7 @@
from requests.exceptions import Timeout
from pywikibot import Site, config, sleep, warning
+from pywikibot.backports import Dict, List
from pywikibot.comms import http
from pywikibot.exceptions import Error, TimeoutError
@@ -89,8 +90,11 @@
"""
return self.last_response
- def select(self, query: str, full_data: bool = False,
- headers=DEFAULT_HEADERS):
+ def select(self,
+ query: str,
+ full_data: bool = False,
+ headers: Optional[Dict[str, str]] = None
+ ) -> Optional[List[Dict[str, str]]]:
"""
Run SPARQL query and return the result.
@@ -99,37 +103,43 @@
:param query: Query text
:param full_data: Whether return full data objects or only values
- :return: List of query results or None if query failed
"""
- data = self.query(query, headers=headers)
- if data and 'results' in data:
- result = []
- qvars = data['head']['vars']
- for row in data['results']['bindings']:
- values = {}
- for var in qvars:
- if var not in row:
- # var is not available (OPTIONAL is probably used)
- values[var] = None
- elif full_data:
- if row[var]['type'] not in VALUE_TYPES:
- raise ValueError('Unknown type: {}'
- .format(row[var]['type']))
- valtype = VALUE_TYPES[row[var]['type']]
- values[var] = valtype(row[var],
- entity_url=self.entity_url)
- else:
- values[var] = row[var]['value']
- result.append(values)
- return result
- return None
+ if headers is None:
+ headers = DEFAULT_HEADERS
- def query(self, query: str, headers=DEFAULT_HEADERS):
+ data = self.query(query, headers=headers)
+ if not data or 'results' not in data:
+ return None
+
+ result = []
+ qvars = data['head']['vars']
+ for row in data['results']['bindings']:
+ values = {}
+ for var in qvars:
+ if var not in row:
+ # var is not available (OPTIONAL is probably used)
+ values[var] = None
+ elif full_data:
+ if row[var]['type'] not in VALUE_TYPES:
+ raise ValueError('Unknown type: {}'
+ .format(row[var]['type']))
+ valtype = VALUE_TYPES[row[var]['type']]
+ values[var] = valtype(row[var],
+ entity_url=self.entity_url)
+ else:
+ values[var] = row[var]['value']
+ result.append(values)
+ return result
+
+ def query(self, query: str, headers: Optional[Dict[str, str]] = None):
"""
Run SPARQL query and return parsed JSON result.
:param query: Query text
"""
+ if headers is None:
+ headers = DEFAULT_HEADERS
+
url = '{}?query={}'.format(self.endpoint, quote(query))
while True:
try:
@@ -137,12 +147,16 @@
except Timeout:
self.wait()
continue
+
if not self.last_response.text:
- return None
+ break
+
try:
return json.loads(self.last_response.text)
except ValueError:
- return None
+ break
+
+ return None
def wait(self):
"""Determine how long to wait after a failed request."""
@@ -154,12 +168,15 @@
# double the next wait, but do not exceed config.retry_max seconds
self.retry_wait = min(config.retry_max, self.retry_wait * 2)
- def ask(self, query: str, headers=DEFAULT_HEADERS) -> bool:
+ def ask(self, query: str,
+ headers: Optional[Dict[str, str]] = None) -> bool:
"""
Run SPARQL ASK query and return boolean result.
:param query: Query text
"""
+ if headers is None:
+ headers = DEFAULT_HEADERS
data = self.query(query, headers=headers)
return data['boolean']
diff --git a/pywikibot/site/_generators.py b/pywikibot/site/_generators.py
index 36872ea..d73e8fa 100644
--- a/pywikibot/site/_generators.py
+++ b/pywikibot/site/_generators.py
@@ -1,6 +1,6 @@
"""Objects representing API generators to MediaWiki site."""
#
-# (C) Pywikibot team, 2008-2021
+# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
@@ -1703,9 +1703,8 @@
"""
# If patrol is not enabled, attr will be set the first time a
# request is done.
- if hasattr(self, '_patroldisabled'):
- if self._patroldisabled:
- return
+ if hasattr(self, '_patroldisabled') and self._patroldisabled:
+ return
if all(_ is None for _ in [rcid, revid, revision]):
raise Error('No rcid, revid or revision provided.')
diff --git a/pywikibot/site/_siteinfo.py b/pywikibot/site/_siteinfo.py
index bc08522..af88274 100644
--- a/pywikibot/site/_siteinfo.py
+++ b/pywikibot/site/_siteinfo.py
@@ -1,6 +1,6 @@
"""Objects representing site info data contents."""
#
-# (C) Pywikibot team, 2008-2020
+# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
@@ -101,7 +101,7 @@
# query this method to actually get the version number
# Convert boolean props from empty strings to actual boolean values
- if prop in Siteinfo.BOOLEAN_PROPS.keys():
+ if prop in Siteinfo.BOOLEAN_PROPS:
# siprop=namespaces and
# magicwords has properties per item in result
if prop in ('namespaces', 'magicwords'):
diff --git a/pywikibot/throttle.py b/pywikibot/throttle.py
index 71b7a1d..e9566c8 100644
--- a/pywikibot/throttle.py
+++ b/pywikibot/throttle.py
@@ -1,6 +1,6 @@
"""Mechanics to slow down wiki read and/or write rate."""
#
-# (C) Pywikibot team, 2008-2021
+# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
@@ -326,5 +326,4 @@
def get_pid(self, module: str) -> int:
"""Get the global pid if the module is running multiple times."""
- global pid
return pid if self.modules[self._module_hash(module)] > 1 else 0
diff --git a/pywikibot/userinterfaces/win32_unicode.py b/pywikibot/userinterfaces/win32_unicode.py
index 3101e11..4e12897 100755
--- a/pywikibot/userinterfaces/win32_unicode.py
+++ b/pywikibot/userinterfaces/win32_unicode.py
@@ -1,6 +1,6 @@
"""Stdout, stderr and argv support for unicode."""
#
-# (C) Pywikibot team, 2012-2021
+# (C) Pywikibot team, 2012-2022
#
##############################################
# Support for unicode in Windows cmd.exe
@@ -28,6 +28,9 @@
from ctypes import c_void_p as LPVOID
from ctypes import create_unicode_buffer, sizeof
from io import IOBase, UnsupportedOperation
+from typing import IO
+
+from pywikibot.backports import List, Tuple
OSWIN32 = (sys.platform == 'win32')
@@ -224,7 +227,7 @@
WinError()
-def get_unicode_console():
+def get_unicode_console() -> Tuple[IO, IO, IO, List[str]]:
"""
Get Unicode console objects.
@@ -238,7 +241,7 @@
# and TZOmegaTZIOY
# https://stackoverflow.com/questions/878972/windows-cmd-encoding-change-caus…
- global stdin, stdout, stderr, argv
+ global stdin, stdout, stderr
if not OSWIN32:
return stdin, stdout, stderr, argv
@@ -323,4 +326,4 @@
_complain('exception {!r} while fixing up sys.stdout and sys.stderr'
.format(e))
- return stdin, stdout, stderr, argv
+ return stdin, stdout, stderr
diff --git a/scripts/interwiki.py b/scripts/interwiki.py
index 0d31dc6..ea51ffb 100755
--- a/scripts/interwiki.py
+++ b/scripts/interwiki.py
@@ -328,7 +328,7 @@
"""
#
-# (C) Pywikibot team, 2003-2021
+# (C) Pywikibot team, 2003-2022
#
# Distributed under the terms of the MIT license.
#
@@ -2414,9 +2414,8 @@
elif arg.startswith('-until:'):
until = arg[7:]
else:
- if not genFactory.handle_arg(arg):
- if not singlePageTitle:
- singlePageTitle = arg
+ if not genFactory.handle_arg(arg) and not singlePageTitle:
+ singlePageTitle = arg
# Do not use additional summary with autonomous mode
if iwconf.autonomous:
diff --git a/scripts/nowcommons.py b/scripts/nowcommons.py
index 794f6de..7229c3b 100755
--- a/scripts/nowcommons.py
+++ b/scripts/nowcommons.py
@@ -43,7 +43,7 @@
can be set within a settings file which is scripts.ini by default.
"""
#
-# (C) Pywikibot team, 2006-2021
+# (C) Pywikibot team, 2006-2022
#
# Distributed under the terms of the MIT license.
#
@@ -385,9 +385,11 @@
if arg == '-replacealways':
options['replace'] = True
options['replacealways'] = True
- elif arg.startswith('-'):
- if arg[1:] in ('always', 'replace', 'replaceloose', 'replaceonly'):
- options[arg[1:]] = True
+ elif arg.startswith('-') and arg[1:] in ('always',
+ 'replace',
+ 'replaceloose',
+ 'replaceonly'):
+ options[arg[1:]] = True
bot = NowCommonsDeleteBot(**options)
bot.run()
diff --git a/scripts/patrol.py b/scripts/patrol.py
index f3c5077..0d18317 100755
--- a/scripts/patrol.py
+++ b/scripts/patrol.py
@@ -42,7 +42,7 @@
"""
#
-# (C) Pywikibot team, 2011-2021
+# (C) Pywikibot team, 2011-2022
#
# Distributed under the terms of the MIT license.
#
@@ -307,11 +307,11 @@
.format(username, title))
choice = True
- if not choice and username in self.whitelist:
- if self.in_list(self.whitelist[username], title):
- verbose_output('{} is whitelisted to modify {}'
- .format(username, title))
- choice = True
+ if not choice and username in self.whitelist \
+ and self.in_list(self.whitelist[username], title):
+ verbose_output('{} is whitelisted to modify {}'
+ .format(username, title))
+ choice = True
if self.opt.ask:
choice = pywikibot.input_yn(
@@ -426,10 +426,9 @@
options['whitelist'] = arg[len('-whitelist:'):]
else:
generator = gen_factory.handle_arg(arg)
- if not generator:
- if ':' in arg:
- m = arg.split(':')
- options[m[0]] = m[1]
+ if not generator and ':' in arg:
+ m = arg.split(':')
+ options[m[0]] = m[1]
if usercontribs:
user = pywikibot.User(site, usercontribs)
diff --git a/scripts/redirect.py b/scripts/redirect.py
index a74bb3d..0923db5 100755
--- a/scripts/redirect.py
+++ b/scripts/redirect.py
@@ -66,7 +66,7 @@
¶ms;
"""
#
-# (C) Pywikibot team, 2004-2021
+# (C) Pywikibot team, 2004-2022
#
# Distributed under the terms of the MIT license.
#
@@ -155,10 +155,11 @@
# always print status message after 10000 pages
if readPagesCount % 10000 == 0:
pywikibot.output('{} pages read...'.format(readPagesCount))
- if self.opt.namespaces:
- if pywikibot.Page(self.site, entry.title).namespace() \
- not in self.opt.namespaces:
- continue
+ if self.opt.namespaces and pywikibot.Page(
+ self.site,
+ entry.title).namespace() not in self.opt.namespaces:
+ continue
+
if alsoGetPageTitles:
pageTitles.add(space_to_underscore(pywikibot.Link(entry.title,
self.site)))
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750782
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I2a57f0f726d69c526af2b296e5a3b4856b9499d5
Gerrit-Change-Number: 750782
Gerrit-PatchSet: 3
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: D3r1ck01 <xsavitar.wiki(a)aol.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750723 )
Change subject: [fix] Solve some deepsource antipattern issues
......................................................................
[fix] Solve some deepsource antipattern issues
https://deepsource.io/gh/xqt/pwb/issues?page=2&category=antipattern&analyze…
Change-Id: I9c3d179a5a23418e9acde199a9d1671c74af9239
---
M pywikibot/config.py
M scripts/reflinks.py
M scripts/solve_disambiguation.py
M tests/aspects.py
M tests/interwikimap_tests.py
M tests/oauth_tests.py
M tests/paraminfo_tests.py
7 files changed, 19 insertions(+), 26 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/config.py b/pywikibot/config.py
index 1a7819e..259520a 100644
--- a/pywikibot/config.py
+++ b/pywikibot/config.py
@@ -540,7 +540,7 @@
# ############# EXTERNAL EDITOR SETTINGS ##############
# The command for the editor you want to use. If set to None, a simple Tkinter
# editor will be used.
-editor = os.environ.get('EDITOR', None)
+editor = os.environ.get('EDITOR')
# Warning: DO NOT use an editor which doesn't support Unicode to edit pages!
# You will BREAK non-ASCII symbols!
diff --git a/scripts/reflinks.py b/scripts/reflinks.py
index b3e425e..3623aec 100755
--- a/scripts/reflinks.py
+++ b/scripts/reflinks.py
@@ -720,9 +720,8 @@
new_text = new_text.replace(match.group(), repl)
# Add <references/> when needed, but ignore templates !
- if page.namespace != 10:
- if self.norefbot.lacksReferences(new_text):
- new_text = self.norefbot.addReferences(new_text)
+ if page.namespace != 10 and self.norefbot.lacksReferences(new_text):
+ new_text = self.norefbot.addReferences(new_text)
new_text = self.deduplicator.process(new_text)
old_text = page.text
diff --git a/scripts/solve_disambiguation.py b/scripts/solve_disambiguation.py
index 16506b1..fa380e2 100755
--- a/scripts/solve_disambiguation.py
+++ b/scripts/solve_disambiguation.py
@@ -686,10 +686,9 @@
# Currently scripts may have its own options set
added_keys = []
for key in keys:
- if key != 'generator':
- if key not in self.available_options:
- added_keys.append(key)
- self.available_options[key] = self.disambig_options[key]
+ if key != 'generator' and key not in self.available_options:
+ added_keys.append(key)
+ self.available_options[key] = self.disambig_options[key]
if added_keys:
pywikibot.warning("""\
The following keys were added to available_options:
@@ -1285,9 +1284,9 @@
)
gen = pagegenerators.PreloadingGenerator(gen)
for ref_page in gen:
- if not self.primaryIgnoreManager.isIgnored(ref_page):
- if not self.treat_links(ref_page, page):
- break # next disambig
+ if not self.primaryIgnoreManager.isIgnored(ref_page) \
+ and not self.treat_links(ref_page, page):
+ break # next disambig
# clear alternatives before working on next disambiguation page
self.opt.pos = []
diff --git a/tests/aspects.py b/tests/aspects.py
index dc9da6e..cab9da7 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -729,12 +729,11 @@
# test class dependencies are declarative, this requires the
# test writer explicitly sets 'site=False' so code reviewers
# check that the script invoked by pwb will not load a site.
- if dct.get('pwb'):
- if 'site' not in dct:
- raise Exception(
- '{}: Test classes using pwb must set "site"; add '
- 'site=False if the test script will not use a site'
- .format(name))
+ if dct.get('pwb') and 'site' not in dct:
+ raise Exception(
+ '{}: Test classes using pwb must set "site"; add '
+ 'site=False if the test script will not use a site'
+ .format(name))
# If the 'site' attribute is a false value,
# remove it so it matches 'not site' in pytest.
diff --git a/tests/interwikimap_tests.py b/tests/interwikimap_tests.py
index 47fae45..a96597c 100644
--- a/tests/interwikimap_tests.py
+++ b/tests/interwikimap_tests.py
@@ -99,10 +99,6 @@
iw_site = site.interwiki(prefix)
self.assertEqual(iw_site.family, site.family)
- def test_interwiki_prefix(self, key):
- """Test site.interwiki_prefix method."""
- self.assertTrue(True)
-
class TestInterwikiMapPrefix(TestCase):
diff --git a/tests/oauth_tests.py b/tests/oauth_tests.py
index e33821e..7dc8556 100644
--- a/tests/oauth_tests.py
+++ b/tests/oauth_tests.py
@@ -26,8 +26,8 @@
def _get_oauth_tokens(self):
"""Get valid OAuth tokens from environment variables."""
tokens_env = 'OAUTH_TOKENS_' + self.family.upper()
- tokens = os.environ.get(tokens_env + '_' + self.code.upper(), None)
- tokens = tokens or os.environ.get(tokens_env, None)
+ tokens = os.environ.get(tokens_env + '_' + self.code.upper())
+ tokens = tokens or os.environ.get(tokens_env)
return tuple(tokens.split(':')) if tokens is not None else None
def setUp(self):
diff --git a/tests/paraminfo_tests.py b/tests/paraminfo_tests.py
index b34691f..92f257b 100644
--- a/tests/paraminfo_tests.py
+++ b/tests/paraminfo_tests.py
@@ -95,9 +95,9 @@
mw_ver = self.site.mw_version
- if mw_ver.version >= (1, 27):
- if mw_ver >= '1.27.0-wmf.4' or mw_ver.suffix == 'alpha':
- known.append('categorize')
+ if mw_ver.version >= (1, 27) \
+ and (mw_ver >= '1.27.0-wmf.4' or mw_ver.suffix == 'alpha'):
+ known.append('categorize')
self._check_param_values(self.site, 'query+watchlist', 'type', known)
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750723
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I9c3d179a5a23418e9acde199a9d1671c74af9239
Gerrit-Change-Number: 750723
Gerrit-PatchSet: 2
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: D3r1ck01 <xsavitar.wiki(a)aol.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750720 )
Change subject: [style] fix code style issues
......................................................................
[style] fix code style issues
Deepsource C0325, W0107, C0412, R170
Change-Id: Ieaeef99bb274cb905127f2a02a25fac7bbf4d22c
---
M pywikibot/data/api.py
M pywikibot/exceptions.py
M pywikibot/proofreadpage.py
M pywikibot/site/_generators.py
M pywikibot/site/_obsoletesites.py
M pywikibot/tools/djvu.py
M tests/archive/isbn_tests.py
M tests/utils.py
M tests/weblinkchecker_tests.py
M tests/wikibase_tests.py
10 files changed, 9 insertions(+), 11 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py
index acde07e..eaad672 100644
--- a/pywikibot/data/api.py
+++ b/pywikibot/data/api.py
@@ -222,7 +222,7 @@
"""Emulate the pageset module, which existed until MW 1.24."""
# pageset isn't a module in the new system, so it is emulated, with
# the paraminfo from the query module.
- assert('query' in self._paraminfo)
+ assert 'query' in self._paraminfo
self._paraminfo['pageset'] = {
'name': 'pageset',
diff --git a/pywikibot/exceptions.py b/pywikibot/exceptions.py
index 3655020..ce08846 100644
--- a/pywikibot/exceptions.py
+++ b/pywikibot/exceptions.py
@@ -506,8 +506,6 @@
"""The section specified by # does not exist."""
- pass
-
class NoCreateError(PageSaveRelatedError):
diff --git a/pywikibot/proofreadpage.py b/pywikibot/proofreadpage.py
index 6357816..7c1eed4 100644
--- a/pywikibot/proofreadpage.py
+++ b/pywikibot/proofreadpage.py
@@ -1021,7 +1021,7 @@
if end is None:
end = self.num_pages
- if not (1 <= start <= end <= self.num_pages):
+ if not 1 <= start <= end <= self.num_pages:
raise ValueError('start={}, end={} are not in valid range (1, {})'
.format(start, end, self.num_pages))
diff --git a/pywikibot/site/_generators.py b/pywikibot/site/_generators.py
index 66d03c9..36872ea 100644
--- a/pywikibot/site/_generators.py
+++ b/pywikibot/site/_generators.py
@@ -1506,7 +1506,7 @@
self._check_view_deleted('deletedrevs', prop)
revids = kwargs.pop('revids', None)
- if not (bool(titles) ^ (revids is not None)):
+ if not bool(titles) ^ (revids is not None):
raise Error('deletedrevs: either "titles" or "revids" parameter '
'must be given.')
if revids and self.mw_version < '1.25':
diff --git a/pywikibot/site/_obsoletesites.py b/pywikibot/site/_obsoletesites.py
index f66c9d4..dc11677 100644
--- a/pywikibot/site/_obsoletesites.py
+++ b/pywikibot/site/_obsoletesites.py
@@ -14,8 +14,6 @@
"""Site removed from a family."""
- pass
-
class ClosedSite(APISite):
"""Site closed to read-only mode."""
diff --git a/pywikibot/tools/djvu.py b/pywikibot/tools/djvu.py
index 3474f5f..657ec11 100644
--- a/pywikibot/tools/djvu.py
+++ b/pywikibot/tools/djvu.py
@@ -108,7 +108,7 @@
def wrapper(obj, *args, **kwargs):
n = args[0]
force = kwargs.get('force', False)
- if not (1 <= n <= obj.number_of_images(force=force)):
+ if not 1 <= n <= obj.number_of_images(force=force):
raise ValueError('Page {} not in file {} [{}-{}]'
.format(int(n), obj.file, int(n),
int(obj.number_of_images())))
diff --git a/tests/archive/isbn_tests.py b/tests/archive/isbn_tests.py
index ae9fc0e..b159370 100644
--- a/tests/archive/isbn_tests.py
+++ b/tests/archive/isbn_tests.py
@@ -249,7 +249,6 @@
def editEntity_dummy(self, data=None, **kwargs):
"""Avoid that editEntity writes."""
- pass
def setUpModule(): # noqa: N802
diff --git a/tests/utils.py b/tests/utils.py
index 5b4741d..84defaf 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -167,7 +167,7 @@
if issubclass(warn_msg.category, ResourceWarning) \
and str(warn_msg.message).startswith(
('unclosed <ssl.SSLSocket', 'unclosed <socket.socket')):
- return None
+ return
log.append(warn_msg)
@@ -395,6 +395,7 @@
if bool(code or fam):
return pywikibot.Site(code, fam, self.username(),
interface=DryDataSite)
+ return None
class DryDataSite(DrySite, pywikibot.site.DataSite):
diff --git a/tests/weblinkchecker_tests.py b/tests/weblinkchecker_tests.py
index 6345d3b..9ae1e67 100644
--- a/tests/weblinkchecker_tests.py
+++ b/tests/weblinkchecker_tests.py
@@ -28,10 +28,11 @@
else:
when = datetime.datetime.strptime(date_string, '%Y%m%d')
try:
- return weblinkchecker._get_closest_memento_url(
+ result = weblinkchecker._get_closest_memento_url(
url, when, self.timegate_uri)
except (RequestsConnectionError, MementoClientException) as e:
self.skipTest(e)
+ return result
class TestMementoWebCite(MementoTestCase):
diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py
index c45544f..1231120 100644
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -40,6 +40,7 @@
for page in gen:
if not page.properties().get('wikibase_item'):
return page
+ return None
class WbRepresentationTestCase(WikidataTestCase):
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750720
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ieaeef99bb274cb905127f2a02a25fac7bbf4d22c
Gerrit-Change-Number: 750720
Gerrit-PatchSet: 1
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750637 )
Change subject: [IMPR] Implement a saner command line log
......................................................................
[IMPR] Implement a saner command line log
Use repr string instead of fixes singlequotes
Change-Id: Ib3bceee4e4bd0038e7cd5d2b2bdf7e171b880c7b
---
M pywikibot/editor.py
1 file changed, 2 insertions(+), 2 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/editor.py b/pywikibot/editor.py
index e40be73..600522c 100644
--- a/pywikibot/editor.py
+++ b/pywikibot/editor.py
@@ -1,7 +1,7 @@
#!/usr/bin/python
"""Text editor class for your favourite editor."""
#
-# (C) Pywikibot team, 2004-2020
+# (C) Pywikibot team, 2004-2021
#
# Distributed under the terms of the MIT license.
#
@@ -69,7 +69,7 @@
@staticmethod
def _concat(command: Sequence[str]) -> str:
- return ' '.join("'{}'".format(part) if ' ' in part else part
+ return ' '.join('{!r}'.format(part) if ' ' in part else part
for part in command)
def edit(self, text: str, jumpIndex: Optional[int] = None,
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/750637
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ib3bceee4e4bd0038e7cd5d2b2bdf7e171b880c7b
Gerrit-Change-Number: 750637
Gerrit-PatchSet: 1
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged