jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/678127 )
Change subject: [cleanup] Unnecessary else/elif used after raise ......................................................................
[cleanup] Unnecessary else/elif used after raise
Simple correction for the anti-pattern cited by...
https://deepsource.io/gh/ankitdobhal/pywikibot/issue/PYL-R1720/occurrences/
Bug: T277890 Change-Id: Ib30a56fb108f762bca338cdbe07d8d0fd0b431fd --- M pywikibot/bot.py M pywikibot/bot_choice.py M pywikibot/config2.py M pywikibot/page/__init__.py M pywikibot/pagegenerators.py M pywikibot/site/_apisite.py M pywikibot/site/_datasite.py M pywikibot/site_detect.py M pywikibot/specialbots/_upload.py M pywikibot/tools/__init__.py M pywikibot/tools/formatter.py M scripts/checkimages.py M tests/aspects.py 13 files changed, 80 insertions(+), 78 deletions(-)
Approvals: Xqt: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/bot.py b/pywikibot/bot.py index 5c68925..61f3a06 100644 --- a/pywikibot/bot.py +++ b/pywikibot/bot.py @@ -1494,9 +1494,9 @@ except KeyboardInterrupt: if config.verbose_output: raise - else: - pywikibot.output('\nKeyboardInterrupt during %s bot run...' % - self.__class__.__name__) + + pywikibot.output('\nKeyboardInterrupt during %s bot run...' % + self.__class__.__name__) finally: self.exit()
diff --git a/pywikibot/bot_choice.py b/pywikibot/bot_choice.py index 0575e49..3c5e874 100755 --- a/pywikibot/bot_choice.py +++ b/pywikibot/bot_choice.py @@ -410,8 +410,8 @@ """Return a string showing the range.""" if not self._list: raise ValueError('The sequence is empty.') - else: - return super().format(default=default) + + return super().format(default=default)
@property def maximum(self) -> int: diff --git a/pywikibot/config2.py b/pywikibot/config2.py index 7e1680c..f137fd1 100644 --- a/pywikibot/config2.py +++ b/pywikibot/config2.py @@ -370,7 +370,8 @@ ' Directory where user-config.py is searched is determined ' 'as follows:\n\n ') + get_base_dir.__doc__ raise RuntimeError(exc_text) - elif __no_user_config != '2': + + if __no_user_config != '2': output(exc_text)
return base_dir diff --git a/pywikibot/page/__init__.py b/pywikibot/page/__init__.py index 5faa9c0..17a2814 100644 --- a/pywikibot/page/__init__.py +++ b/pywikibot/page/__init__.py @@ -3026,8 +3026,8 @@ except APIError as err: if err.code == 'invalidrange': raise ValueError('%s is not a valid IP range.' % self.username) - else: - raise err + + raise err
def unblock(self, reason: Optional[str] = None): """ @@ -4021,10 +4021,11 @@ """ if force or not hasattr(self, '_content'): self.get(force=force) + if site not in self.sitelinks: raise pywikibot.NoPage(self) - else: - return self.sitelinks[site].canonical_title() + + return self.sitelinks[site].canonical_title()
def setSitelink(self, sitelink, **kwargs): """ @@ -5306,7 +5307,8 @@ if not t: raise pywikibot.InvalidTitle( "'{0}' has no title.".format(self._text)) - elif ':' in t and self._namespace >= 0: # < 0 don't have talk + + if ':' in t and self._namespace >= 0: # < 0 don't have talk other_ns = self._site.namespaces[self._namespace - 1 if self._namespace % 2 else self._namespace + 1] diff --git a/pywikibot/pagegenerators.py b/pywikibot/pagegenerators.py index 33a9ce4..fbc585f 100644 --- a/pywikibot/pagegenerators.py +++ b/pywikibot/pagegenerators.py @@ -899,7 +899,7 @@ rctag = params.pop(0) if len(params) > 2: raise ValueError('More than two parameters passed.') - elif len(params) == 2: + if len(params) == 2: offset = float(params[0]) duration = float(params[1]) if offset < 0 or duration < 0: diff --git a/pywikibot/site/_apisite.py b/pywikibot/site/_apisite.py index 951530e..eb94bae 100644 --- a/pywikibot/site/_apisite.py +++ b/pywikibot/site/_apisite.py @@ -1280,11 +1280,11 @@ # Check if target is on another site. if target.site != page.site: raise InterwikiRedirectPage(page, target) - else: - # Redirect to Special: & Media: pages, which do not work - # like redirects, but are rendered like a redirect. - page._redirtarget = target - return page._redirtarget + + # Redirect to Special: & Media: pages, which do not work + # like redirects, but are rendered like a redirect. + page._redirtarget = target + return page._redirtarget
pagedata = list(result['query']['pages'].values())[0] # There should be only one value in 'pages' (the ultimate @@ -1665,11 +1665,10 @@ 'info': err.info } raise Error(exception % errdata) - elif issubclass(exception, SpamblacklistError): + if issubclass(exception, SpamblacklistError): urls = ', '.join(err.other[err.code]['matches']) raise exception(page, url=urls) from None - else: - raise exception(page) + raise exception(page) pywikibot.debug( "editpage: Unexpected error code '%s' received." % err.code, @@ -1833,13 +1832,13 @@ if err.code in self._mh_errors: on_error = self._mh_errors[err.code] raise Error(on_error.format_map(errdata)) - else: - pywikibot.debug( - "mergehistory: Unexpected error code '{code}' received" - .format(code=err.code), - _logger - ) - raise + + pywikibot.debug( + "mergehistory: Unexpected error code '{code}' received" + .format(code=err.code), + _logger + ) + raise finally: self.unlock_page(source) self.unlock_page(dest) @@ -1945,16 +1944,18 @@ else: failed_page = newpage if on_error.on_new_page else page raise on_error.exception(failed_page) - else: - errdata = { - 'site': self, - 'oldtitle': oldtitle, - 'oldnamespace': self.namespace(page.namespace()), - 'newtitle': newtitle, - 'newnamespace': self.namespace(newlink.namespace), - 'user': self.user(), - } - raise Error(on_error % errdata) + + errdata = { + 'site': self, + 'oldtitle': oldtitle, + 'oldnamespace': self.namespace(page.namespace()), + 'newtitle': newtitle, + 'newnamespace': self.namespace(newlink.namespace), + 'user': self.user(), + } + + raise Error(on_error % errdata) + pywikibot.debug("movepage: Unexpected error code '%s' received." % err.code, _logger) @@ -2932,7 +2933,7 @@ % {'msg': message}, file_key=_file_key, offset=result.get('offset', False)) - elif 'result' not in result: + if 'result' not in result: pywikibot.output('Upload: unrecognized response: %s' % result)
if result['result'] == 'Success': diff --git a/pywikibot/site/_datasite.py b/pywikibot/site/_datasite.py index 43f8524..9d27f7c 100644 --- a/pywikibot/site/_datasite.py +++ b/pywikibot/site/_datasite.py @@ -768,10 +768,10 @@ if 'site' in kwargs: if kwargs['site'].sitename != self.sitename: raise ValueError('The site given in the kwargs is different.') - else: - warn('search_entities should not get a site via kwargs.', - UserWarning, 2) - del kwargs['site'] + + warn('search_entities should not get a site via kwargs.', + UserWarning, 2) + del kwargs['site']
parameters = dict(search=search, language=language, **kwargs) gen = self._generator(api.APIGenerator, diff --git a/pywikibot/site_detect.py b/pywikibot/site_detect.py index a210bf6..b509fb0 100644 --- a/pywikibot/site_detect.py +++ b/pywikibot/site_detect.py @@ -275,9 +275,9 @@ """Raise ServerError if the response indicates a server error.""" if response.status_code == 503: raise ServerError('Service Unavailable') - elif response.status_code == 502: + if response.status_code == 502: raise ServerError('Bad Gateway') - elif response.status_code == 500: + if response.status_code == 500: raise ServerError('Internal Server Error') - elif response.status_code == 200 and SERVER_DB_ERROR_MSG in response.text: + if response.status_code == 200 and SERVER_DB_ERROR_MSG in response.text: raise ServerError('Server cannot access the database') diff --git a/pywikibot/specialbots/_upload.py b/pywikibot/specialbots/_upload.py index 9c53532..5f76d8f 100644 --- a/pywikibot/specialbots/_upload.py +++ b/pywikibot/specialbots/_upload.py @@ -446,8 +446,8 @@ except KeyboardInterrupt: if config.verbose_output: raise - else: - pywikibot.output('\nKeyboardInterrupt during %s bot run...' % - self.__class__.__name__) + + pywikibot.output('\nKeyboardInterrupt during %s bot run...' % + self.__class__.__name__) finally: self.exit() diff --git a/pywikibot/tools/__init__.py b/pywikibot/tools/__init__.py index 70caa5f..f891c09 100644 --- a/pywikibot/tools/__init__.py +++ b/pywikibot/tools/__init__.py @@ -427,18 +427,18 @@
def __getattr__(self, attr): """Compile the regex and delegate all attribute to the regex.""" - if self._raw: - if not self._compiled: - self._compiled = re.compile(self.raw, self.flags) - - if hasattr(self._compiled, attr): - return getattr(self._compiled, attr) - - raise AttributeError('%s: attr %s not recognised' - % (self.__class__.__name__, attr)) - else: + if not self._raw: raise AttributeError('%s.raw not set' % self.__class__.__name__)
+ if not self._compiled: + self._compiled = re.compile(self.raw, self.flags) + + if hasattr(self._compiled, attr): + return getattr(self._compiled, attr) + + raise AttributeError('%s: attr %s not recognised' + % (self.__class__.__name__, attr)) +
class DeprecatedRegex(LazyRegex):
diff --git a/pywikibot/tools/formatter.py b/pywikibot/tools/formatter.py index a893dbd..def2fdc 100644 --- a/pywikibot/tools/formatter.py +++ b/pywikibot/tools/formatter.py @@ -82,17 +82,16 @@ raise ValueError( 'Color field "{0}" in "{1}" uses format spec ' 'information "{2}"'.format(field, format_string, spec)) - elif conv: + if conv: raise ValueError( 'Color field "{0}" in "{1}" uses conversion ' 'information "{2}"'.format(field, format_string, conv)) - else: - if not literal or literal[-1] != '\03': - literal += '\03' - if '\03' in literal[:-1]: - raise ValueError(r'Literal text in {0} contains ' - r'\03'.format(format_string)) - previous_literal += literal + '{' + field + '}' + if not literal or literal[-1] != '\03': + literal += '\03' + if '\03' in literal[:-1]: + raise ValueError(r'Literal text in {0} contains ' + r'\03'.format(format_string)) + previous_literal += literal + '{' + field + '}' else: if '\03' in literal: raise ValueError(r'Literal text in {0} contains ' diff --git a/scripts/checkimages.py b/scripts/checkimages.py index acc30af..800af2a 100755 --- a/scripts/checkimages.py +++ b/scripts/checkimages.py @@ -1026,13 +1026,13 @@ raise LogIsFull( 'The log page ({}) is full! Please delete the old files ' 'reported.'.format(another_page.title())) - else: - pywikibot.output( - 'The log page ({}) is full! Please delete the old files ' - ' reported. Skip!'.format(another_page.title())) - # Don't report, but continue with the check - # (we don't know if this is the first time we check this file - # or not) + + pywikibot.output( + 'The log page ({}) is full! Please delete the old files ' + ' reported. Skip!'.format(another_page.title())) + # Don't report, but continue with the check + # (we don't know if this is the first time we check this file + # or not) else: # Adding the log another_page.put(text_get + rep_text, summary=com, force=True, diff --git a/tests/aspects.py b/tests/aspects.py index f814813..18caee2 100644 --- a/tests/aspects.py +++ b/tests/aspects.py @@ -195,8 +195,8 @@ raise unittest.SkipTest('Pages in namespaces {!r} not found.' .format( list(namespaces - page_namespaces))) - else: - self.assertEqual(page_namespaces, namespaces) + + self.assertEqual(page_namespaces, namespaces)
def assertPageTitlesEqual(self, gen, titles, site=None): """ @@ -440,11 +440,10 @@ '{}: hostname {} failed (cached): {}' .format(cls.__name__, hostname, cls._checked_hostnames[hostname])) - elif cls._checked_hostnames[hostname] is False: + if cls._checked_hostnames[hostname] is False: raise unittest.SkipTest('{}: hostname {} failed (cached)' .format(cls.__name__, hostname)) - else: - continue + continue
try: if '://' not in hostname:
pywikibot-commits@lists.wikimedia.org