jenkins-bot submitted this change.

View Change

Approvals: Xqt: Looks good to me, approved jenkins-bot: Verified
[cleanup] Removal of unnecessary else / elif usage after return

Unnecessary else / elif usage after return statements.
These changes serve to comply with the Coding Convention Guidlines.

Bug: T277888
Change-Id: I32cf4ef18183acbb518823f9ae86bf4693f72e5d
---
M pywikibot/__init__.py
M pywikibot/bot.py
M pywikibot/bot_choice.py
M pywikibot/comms/http.py
M pywikibot/config2.py
M pywikibot/cosmetic_changes.py
M pywikibot/daemonize.py
M pywikibot/data/sparql.py
M pywikibot/date.py
M pywikibot/diff.py
M pywikibot/family.py
M pywikibot/i18n.py
M pywikibot/page/__init__.py
M pywikibot/pagegenerators.py
M pywikibot/proofreadpage.py
M pywikibot/site/_apisite.py
M pywikibot/site/_basesite.py
M pywikibot/site/_interwikimap.py
M pywikibot/site/_namespace.py
M pywikibot/site/_siteinfo.py
M pywikibot/site/_tokenwallet.py
M pywikibot/specialbots/_upload.py
M pywikibot/textlib.py
M pywikibot/tools/__init__.py
M pywikibot/tools/formatter.py
M pywikibot/userinterfaces/terminal_interface_base.py
M pywikibot/userinterfaces/transliteration.py
M scripts/add_text.py
M scripts/archive/casechecker.py
M scripts/archive/commonscat.py
M scripts/archive/flickrripper.py
M scripts/archive/imageuncat.py
M scripts/archive/interwiki.py
M scripts/archive/lonelypages.py
M scripts/archive/match_images.py
M scripts/archive/nowcommons.py
M scripts/archive/spamremove.py
M scripts/archivebot.py
M scripts/category.py
M scripts/checkimages.py
M scripts/clean_sandbox.py
M scripts/harvest_template.py
M scripts/listpages.py
M scripts/replace.py
M scripts/solve_disambiguation.py
M tests/archive/disambredir_tests.py
M tests/aspects.py
M tests/plural_tests.py
M tests/textlib_tests.py
M tests/utils.py
50 files changed, 181 insertions(+), 267 deletions(-)

diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index 76d3fe2..5d149b5 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -665,7 +665,7 @@
"""
if isinstance(value, Decimal):
return value
- elif value is None:
+ if value is None:
return None
return Decimal(str(value))

diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index 2e8900e..5c68925 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -633,8 +633,7 @@
break
self._current_match = None # don't reset in case of an exception
return answer
- else:
- return None
+ return None

@property
def choices(self):
@@ -2173,8 +2172,7 @@
result = self.user_edit_entity(item, data, summary=summary, **kwargs)
if result:
return item
- else:
- return None
+ return None

def treat_page(self):
"""Treat a page."""
diff --git a/pywikibot/bot_choice.py b/pywikibot/bot_choice.py
index 9c2601d..0575e49 100755
--- a/pywikibot/bot_choice.py
+++ b/pywikibot/bot_choice.py
@@ -67,8 +67,7 @@
"""
if self.test(value):
return self
- else:
- return None
+ return None

def format(self, default=None):
"""Return a formatted string for that option."""
@@ -128,8 +127,7 @@
return '{0}[{1}]{2}'.format(
self.option[:index], shortcut,
self.option[index + len(self.shortcut):])
- else:
- return '{0} [{1}]'.format(self.option, shortcut)
+ return '{0} [{1}]'.format(self.option, shortcut)

def result(self, value):
"""Return the lowercased shortcut."""
@@ -388,8 +386,7 @@
"""Return integer from value with prefix removed."""
if value.lower().startswith(self.prefix.lower()):
return int(value[len(self.prefix):])
- else:
- raise ValueError('Value does not start with prefix')
+ raise ValueError('Value does not start with prefix')

def result(self, value):
"""Return the value converted into int."""
diff --git a/pywikibot/comms/http.py b/pywikibot/comms/http.py
index 05f8bd2..98ec743 100644
--- a/pywikibot/comms/http.py
+++ b/pywikibot/comms/http.py
@@ -360,9 +360,8 @@
def assign_user_agent(user_agent_format_string):
if not user_agent_format_string or '{' in user_agent_format_string:
return user_agent(None, user_agent_format_string)
- else:
- # do nothing, it is already a UA
- return user_agent_format_string
+ # do nothing, it is already a UA
+ return user_agent_format_string

# If not already specified.
if 'user-agent' not in headers:
diff --git a/pywikibot/config2.py b/pywikibot/config2.py
index 600c130..9d0573a 100644
--- a/pywikibot/config2.py
+++ b/pywikibot/config2.py
@@ -308,8 +308,7 @@
directory = os.path.abspath(directory)
if directory == test_directory:
return True
- else:
- return os.path.exists(os.path.join(directory, 'user-config.py'))
+ return os.path.exists(os.path.join(directory, 'user-config.py'))

if test_directory is not None:
test_directory = os.path.abspath(test_directory)
@@ -902,18 +901,16 @@
if (value is None or default_value is None
or isinstance(value, type(default_value))):
return value
- elif isinstance(value, int) and isinstance(default_value, float):
+ if isinstance(value, int) and isinstance(default_value, float):
return float(value)
- else:
- raise _DifferentTypeError(name, type(value), [type(default_value)])
+ raise _DifferentTypeError(name, type(value), [type(default_value)])


def _assert_types(name, value, types):
"""Return the value if it's one of the types."""
if isinstance(value, types):
return value
- else:
- raise _DifferentTypeError(name, type(value), types)
+ raise _DifferentTypeError(name, type(value), types)


DEPRECATED_VARIABLE = (
diff --git a/pywikibot/cosmetic_changes.py b/pywikibot/cosmetic_changes.py
index f80e5a3..8ef0bfd 100755
--- a/pywikibot/cosmetic_changes.py
+++ b/pywikibot/cosmetic_changes.py
@@ -323,8 +323,7 @@
.format(self.title))
pywikibot.exception(e)
return False
- else:
- raise
+ raise
else:
if self.show_diff:
pywikibot.showDiff(text, new_text)
diff --git a/pywikibot/daemonize.py b/pywikibot/daemonize.py
index e5f6093..6b70a9f 100644
--- a/pywikibot/daemonize.py
+++ b/pywikibot/daemonize.py
@@ -59,11 +59,10 @@
if chdir:
os.chdir('/')
return
- else:
- # Write out the pid
- path = os.path.basename(sys.argv[0]) + '.pid'
- with codecs.open(path, 'w', 'utf-8') as f:
- f.write(str(pid))
+ # Write out the pid
+ path = os.path.basename(sys.argv[0]) + '.pid'
+ with codecs.open(path, 'w', 'utf-8') as f:
+ f.write(str(pid))
# Exit to return control to the terminal
# os._exit to prevent the cleanup to run
os._exit(0)
diff --git a/pywikibot/data/sparql.py b/pywikibot/data/sparql.py
index 434a3ba..7dcf6e3 100644
--- a/pywikibot/data/sparql.py
+++ b/pywikibot/data/sparql.py
@@ -213,8 +213,7 @@
urllen = len(self.entity_url)
if self.value.startswith(self.entity_url):
return self.value[urllen:]
- else:
- return None
+ return None

def __repr__(self):
return '<' + self.value + '>'
diff --git a/pywikibot/date.py b/pywikibot/date.py
index 68d9f37..a825e67 100644
--- a/pywikibot/date.py
+++ b/pywikibot/date.py
@@ -284,8 +284,7 @@
tmp = value.translate(digitsToLocalDict) # Test
if tmp == value:
return int(value.translate(localToDigitsDict)) # Convert
- else:
- raise ValueError('string contains regular digits')
+ raise ValueError('string contains regular digits')


# Helper for roman numerals number representation
@@ -456,12 +455,11 @@
params = tuple(_make_parameter(decoders[i], param)
for i, param in enumerate(params))
return strPattern % params
- else:
- assert len(decoders) == 1, (
- 'A single parameter does not match {0} decoders.'
- .format(len(decoders)))
- # convert integer parameter into its textual representation
- return strPattern % _make_parameter(decoders[0], params)
+ assert len(decoders) == 1, (
+ 'A single parameter does not match {0} decoders.'
+ .format(len(decoders)))
+ # convert integer parameter into its textual representation
+ return strPattern % _make_parameter(decoders[0], params)


@dh.register(str)
@@ -1668,7 +1666,7 @@
"""
if makeUpperCase is None:
return [pattern % monthName(lang, m) for m in range(1, 13)]
- elif makeUpperCase:
+ if makeUpperCase:
f = first_upper
else:
f = first_lower
@@ -1983,8 +1981,7 @@
"""Return year name in a language."""
if year < 0:
return formats['YearBC'][lang](-year)
- else:
- return formats['YearAD'][lang](year)
+ return formats['YearAD'][lang](year)


def apply_month_delta(date, month_delta=1, add_overlap=False):
diff --git a/pywikibot/diff.py b/pywikibot/diff.py
index 777b260..8eb6023 100644
--- a/pywikibot/diff.py
+++ b/pywikibot/diff.py
@@ -158,8 +158,7 @@
colored_line = color_format('{color}{0}{default}',
line, color=self.colors[color])
return colored_line
- else:
- return line
+ return line

colored_line = ''
color_closed = True
diff --git a/pywikibot/family.py b/pywikibot/family.py
index 3125a40..2ec1a09 100644
--- a/pywikibot/family.py
+++ b/pywikibot/family.py
@@ -1173,7 +1173,7 @@
if cls.name in (cls.multi_language_content_families
+ cls.other_content_families):
return cls.name + '.org'
- elif cls.name in cls.wikimedia_org_families:
+ if cls.name in cls.wikimedia_org_families:
return 'wikimedia.org'

raise NotImplementedError(
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py
index 3c4c96e..2ce4c0d 100644
--- a/pywikibot/i18n.py
+++ b/pywikibot/i18n.py
@@ -786,8 +786,7 @@

if not only_plural and parameters:
return trans % parameters
- else:
- return trans
+ return trans


@deprecated('twtranslate', since='20151009', future_warning=True)
diff --git a/pywikibot/page/__init__.py b/pywikibot/page/__init__.py
index ed09333..233113f 100644
--- a/pywikibot/page/__init__.py
+++ b/pywikibot/page/__init__.py
@@ -311,8 +311,7 @@
with_ns = True
if with_ns:
return '[[%s%s]]' % (title, section)
- else:
- return '[[%s%s|%s]]' % (title, section, label)
+ return '[[%s%s|%s]]' % (title, section, label)
if not with_ns and self.namespace() != 0:
title = label + section
else:
@@ -439,8 +438,7 @@
if (hasattr(self, '_revid') and self._revid in self._revisions
and self._revisions[self._revid].text is not None):
return self._revisions[self._revid]
- else:
- return None
+ return None

def _getInternals(self):
"""
@@ -978,11 +976,10 @@
p_types = set(self.site.protection_types())
if not self.exists():
return {'create'} if 'create' in p_types else set()
- else:
- p_types.remove('create') # no existing page allows that
- if not self.is_filepage(): # only file pages allow upload
- p_types.remove('upload')
- return p_types
+ p_types.remove('create') # no existing page allows that
+ if not self.is_filepage(): # only file pages allow upload
+ p_types.remove('upload')
+ return p_types

def has_permission(self, action: str = 'edit') -> bool:
"""Determine whether the page can be modified.
@@ -1407,8 +1404,7 @@

if include_obsolete:
return self._langlinks
- else:
- return [i for i in self._langlinks if not i.site.obsolete]
+ return [i for i in self._langlinks if not i.site.obsolete]

def iterlanglinks(self,
total: Optional[int] = None,
@@ -2477,11 +2473,10 @@

sha1 = compute_file_hash(filename)
return sha1 == revision.sha1
- else:
- pywikibot.warning(
- 'Unsuccessfull request ({}): {}'
- .format(req.status_code, req.url))
- return False
+ pywikibot.warning(
+ 'Unsuccessfull request ({}): {}'
+ .format(req.status_code, req.url))
+ return False

def globalusage(self, total=None):
"""
@@ -2841,8 +2836,7 @@
"""
if self._isAutoblock:
return '#' + self.title(with_ns=False)
- else:
- return self.title(with_ns=False)
+ return self.title(with_ns=False)

def isRegistered(self, force: bool = False) -> bool:
"""
@@ -3226,9 +3220,8 @@
if self.id != '-1':
return 'pywikibot.page.{0}({1!r}, {2!r})'.format(
self.__class__.__name__, self.repo, self.id)
- else:
- return 'pywikibot.page.{0}({1!r})'.format(
- self.__class__.__name__, self.repo)
+ return 'pywikibot.page.{0}({1!r})'.format(
+ self.__class__.__name__, self.repo)

@classmethod
def is_valid_id(cls, entity_id: str) -> bool:
@@ -3248,8 +3241,7 @@
for key, cls in self.DATA_ATTRIBUTES.items():
setattr(self, key, cls.new_empty(self.repo))
return getattr(self, name)
- else:
- return self.get()[name]
+ return self.get()[name]

return super().__getattr__(name)

@@ -3280,8 +3272,7 @@
"""
if numeric:
return int(self.id[1:]) if self.id != '-1' else -1
- else:
- return self.id
+ return self.id

def get_data_for_new_entity(self) -> dict:
"""
@@ -4214,8 +4205,7 @@
"""
if numeric:
return int(self.id[1:])
- else:
- return self.id
+ return self.id


class PropertyPage(WikibasePage, Property):
@@ -4979,8 +4969,7 @@
ns = self.site.namespaces.lookup_name(self._nskey)
if ns:
return ns
- else:
- self._nskey = default_nskey
+ self._nskey = default_nskey

if isinstance(self._nskey, int):
try:
@@ -5021,8 +5010,7 @@
if self.namespace != Namespace.MAIN:
return '%s:%s' % (self.site.namespace(self.namespace),
self.title)
- else:
- return self.title
+ return self.title

def ns_title(self, onsite=None):
"""
@@ -5051,8 +5039,7 @@

if self.namespace != Namespace.MAIN:
return '%s:%s' % (name, self.title)
- else:
- return self.title
+ return self.title

def astext(self, onsite=None):
"""
diff --git a/pywikibot/pagegenerators.py b/pywikibot/pagegenerators.py
index 228e89d..33a9ce4 100644
--- a/pywikibot/pagegenerators.py
+++ b/pywikibot/pagegenerators.py
@@ -574,7 +574,7 @@
pywikibot.warning('filter(s) specified but no generators.')
return None

- elif len(self.gens) == 1:
+ if len(self.gens) == 1:
dupfiltergen = self.gens[0]
if hasattr(self, '_single_gen_filter_unique'):
dupfiltergen = _filter_unique_pages(dupfiltergen)
diff --git a/pywikibot/proofreadpage.py b/pywikibot/proofreadpage.py
index f6fe401..92ec48e 100644
--- a/pywikibot/proofreadpage.py
+++ b/pywikibot/proofreadpage.py
@@ -118,8 +118,7 @@
"""Return a string representation."""
if self._has_div:
return FullHeader.TEMPLATE_V1.format(self)
- else:
- return FullHeader.TEMPLATE_V2.format(self)
+ return FullHeader.TEMPLATE_V2.format(self)


class ProofreadPage(pywikibot.Page):
@@ -638,8 +637,7 @@
if error:
pywikibot.error('OCR query %s: %s' % (cmd_uri, _text))
return error, _text
- else:
- return error, parser_func(_text)
+ return error, parser_func(_text)

def _do_hocr(self):
"""Do hocr using https://phetools.toolforge.org/hocr_cgi.py?cmd=hocr.
@@ -734,9 +732,8 @@

if not error:
return text
- else:
- raise ValueError(
- '{0}: not possible to perform OCR. {1}'.format(self, text))
+ raise ValueError(
+ '{0}: not possible to perform OCR. {1}'.format(self, text))


class PurgeRequest(Request):
@@ -811,8 +808,7 @@
title = p_href.search(href)
if title:
return title.group(1)
- else:
- return None
+ return None

def save(self, *args, **kwargs): # See Page.save().
"""
diff --git a/pywikibot/site/_apisite.py b/pywikibot/site/_apisite.py
index b5a5417..4832990 100644
--- a/pywikibot/site/_apisite.py
+++ b/pywikibot/site/_apisite.py
@@ -276,8 +276,7 @@
# and kwargs here are actually in parameters mode.
if 'expiry' in kwargs and kwargs['expiry'] is not None:
return api.CachedRequest
- else:
- return api.Request
+ return api.Request

def _request(self, **kwargs):
"""Create a request by forwarding all parameters directly."""
@@ -847,8 +846,7 @@

if word in self._magicwords:
return self._magicwords[word]
- else:
- return [word]
+ return [word]

@deprecated('expand_text', since='20150831', future_warning=True)
def resolvemagicwords(self, wikitext): # pragma: no cover
@@ -4982,9 +4980,8 @@
return self._generator(
api.PageGenerator, type_arg='protectedtitles',
namespaces=namespaces, gptlevel=level, total=total)
- else:
- return self.allpages(namespace=namespaces[0], protect_level=level,
- protect_type=type, total=total)
+ return self.allpages(namespace=namespaces[0], protect_level=level,
+ protect_type=type, total=total)

def get_property_names(self, force: bool = False):
"""
@@ -5035,14 +5032,13 @@
def get_param(item):
if isinstance(item, str):
return 'title', item
- elif isinstance(item, pywikibot.Page):
+ if isinstance(item, pywikibot.Page):
return 'title', item.title()
- elif isinstance(item, int):
+ if isinstance(item, int):
return 'rev', item
- elif isinstance(item, pywikibot.page.Revision):
+ if isinstance(item, pywikibot.page.Revision):
return 'rev', item.revid
- else:
- return None
+ return None

old = get_param(old)
if not old:
diff --git a/pywikibot/site/_basesite.py b/pywikibot/site/_basesite.py
index a46bc22..34f9750 100644
--- a/pywikibot/site/_basesite.py
+++ b/pywikibot/site/_basesite.py
@@ -184,8 +184,7 @@
"""Return the currently-logged in bot username, or None."""
if self.logged_in():
return self.username()
- else:
- return None
+ return None

@remove_last_args(['sysop'])
def username(self):
@@ -402,8 +401,7 @@
ns = self.namespaces.lookup_name(ns)
if not delim or not ns:
return default_ns, title
- else:
- return ns, name
+ return ns, name

# Replace underscores with spaces and multiple combinations of them
# with only one space
diff --git a/pywikibot/site/_interwikimap.py b/pywikibot/site/_interwikimap.py
index 18e41c2..8f456b7 100644
--- a/pywikibot/site/_interwikimap.py
+++ b/pywikibot/site/_interwikimap.py
@@ -73,7 +73,7 @@
raise KeyError("'{0}' is not an interwiki prefix.".format(prefix))
if isinstance(self._iw_sites[prefix].site, pywikibot.site.BaseSite):
return self._iw_sites[prefix]
- elif isinstance(self._iw_sites[prefix].site, Exception):
+ if isinstance(self._iw_sites[prefix].site, Exception):
raise self._iw_sites[prefix].site
else:
raise TypeError('_iw_sites[%s] is wrong type: %s'
diff --git a/pywikibot/site/_namespace.py b/pywikibot/site/_namespace.py
index ebc7735..70be918 100644
--- a/pywikibot/site/_namespace.py
+++ b/pywikibot/site/_namespace.py
@@ -124,8 +124,7 @@
def _distinct(self):
if self.custom_name == self.canonical_name:
return [self.canonical_name] + self.aliases
- else:
- return [self.custom_name, self.canonical_name] + self.aliases
+ return [self.custom_name, self.canonical_name] + self.aliases

def _contains_lowercase_name(self, name):
"""Determine a lowercase normalised name is a name of this namespace.
@@ -155,8 +154,7 @@
"""Obtain length of the iterable."""
if self.custom_name == self.canonical_name:
return len(self.aliases) + 1
- else:
- return len(self.aliases) + 2
+ return len(self.aliases) + 2

def __iter__(self):
"""Return an iterator."""
diff --git a/pywikibot/site/_siteinfo.py b/pywikibot/site/_siteinfo.py
index a798040..18d6282 100644
--- a/pywikibot/site/_siteinfo.py
+++ b/pywikibot/site/_siteinfo.py
@@ -141,8 +141,7 @@
invalid_properties.extend(
prop.strip() for prop in matched.group(1).split(','))
return True
- else:
- return False
+ return False

props = [prop] if isinstance(prop, str) else prop
if not props:
@@ -169,14 +168,13 @@
pywikibot.log(
"Unable to get siprop '{0}'".format(props[0]))
return {props[0]: (Siteinfo._get_default(props[0]), False)}
- else:
- pywikibot.log('Unable to get siteinfo, because at least '
- "one property is unknown: '{0}'".format(
- "', '".join(props)))
- results = {}
- for prop in props:
- results.update(self._get_siteinfo(prop, expiry))
- return results
+ pywikibot.log('Unable to get siteinfo, because at least '
+ "one property is unknown: '{0}'".format(
+ "', '".join(props)))
+ results = {}
+ for prop in props:
+ results.update(self._get_siteinfo(prop, expiry))
+ return results
raise
else:
result = {}
@@ -245,8 +243,7 @@
return default_info[key]
if key in self._cache['general'][0]:
return self._cache['general'][0][key], self._cache['general']
- else:
- return None
+ return None

def __getitem__(self, key: str):
"""Return a siteinfo property, caching and not forcing it."""
@@ -318,8 +315,7 @@
if key in self._cache['general'][0]:
return (self._cache['general'][0][key],
self._cache['general'][1])
- else:
- return self._cache[key]
+ return self._cache[key]
raise KeyError(key)

def __contains__(self, key: str) -> bool:
@@ -361,5 +357,4 @@
result = self.get(key, expiry=force)
if not dump:
return result
- else:
- return self._cache
+ return self._cache
diff --git a/pywikibot/site/_tokenwallet.py b/pywikibot/site/_tokenwallet.py
index 6c603eb..e622775 100644
--- a/pywikibot/site/_tokenwallet.py
+++ b/pywikibot/site/_tokenwallet.py
@@ -67,13 +67,12 @@

if key in user_tokens:
return user_tokens[key]
- else:
- # token not allowed for self.site.user() on self.site
- self.failed_cache.add(failed_cache_key)
- # to be changed back to a plain KeyError?
- raise Error(
- "Action '{0}' is not allowed for user {1} on {2} wiki."
- .format(key, self.site.user(), self.site))
+ # token not allowed for self.site.user() on self.site
+ self.failed_cache.add(failed_cache_key)
+ # to be changed back to a plain KeyError?
+ raise Error(
+ "Action '{0}' is not allowed for user {1} on {2} wiki."
+ .format(key, self.site.user(), self.site))

def __contains__(self, key):
"""Return True if the given token name is cached."""
diff --git a/pywikibot/specialbots/_upload.py b/pywikibot/specialbots/_upload.py
index 622c8a3..f2f5329 100644
--- a/pywikibot/specialbots/_upload.py
+++ b/pywikibot/specialbots/_upload.py
@@ -412,8 +412,7 @@
pywikibot.output('Upload of %s successful.' % filename)
self._save_counter += 1
return filename # data['filename']
- else:
- pywikibot.output('Upload aborted.')
+ pywikibot.output('Upload aborted.')
return None

def skip_run(self):
diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py
index cb6c476..c72c9b0 100644
--- a/pywikibot/textlib.py
+++ b/pywikibot/textlib.py
@@ -637,8 +637,7 @@
def replace_callable(link, text, groups, rng):
if replace_list[0] == link:
return replace_list[1]
- else:
- return None
+ return None

def check_classes(replacement):
"""Normalize the replacement into a list."""
@@ -1057,8 +1056,7 @@
newtext = removeLanguageLinks(text, site, mymarker)
mymarker = expandmarker(newtext, mymarker, separator)
return newtext.replace(mymarker, marker)
- else:
- return removeLanguageLinks(text, site, marker)
+ return removeLanguageLinks(text, site, marker)


def replaceLanguageLinks(oldtext: str, new: dict, site=None,
@@ -1339,8 +1337,7 @@
newtext = removeCategoryLinks(text, site, mymarker)
mymarker = expandmarker(newtext, mymarker, separator)
return newtext.replace(mymarker, marker)
- else:
- return removeCategoryLinks(text, site, marker)
+ return removeCategoryLinks(text, site, marker)


def replaceCategoryInPlace(oldtext, oldcat, newcat, site=None,
@@ -1626,8 +1623,7 @@

if use_regex:
return extract_templates_and_params_regex(text, False, strip)
- else:
- return extract_templates_and_params_mwpfh(text, strip)
+ return extract_templates_and_params_mwpfh(text, strip)


def extract_templates_and_params_mwpfh(text: str, strip=False):
@@ -2083,8 +2079,7 @@
else:
txt = pat.sub(marker, txt)
return (txt, m)
- else:
- return (txt, None)
+ return (txt, None)

@staticmethod
def _valid_date_dict_positions(dateDict):
diff --git a/pywikibot/tools/__init__.py b/pywikibot/tools/__init__.py
index 827cf91..2274554 100644
--- a/pywikibot/tools/__init__.py
+++ b/pywikibot/tools/__init__.py
@@ -92,9 +92,8 @@
else:
if module_version >= LooseVersion(version):
return True
- else:
- warn('Module version {} is lower than requested version {}'
- .format(module_version, version), ImportWarning)
+ warn('Module version {} is lower than requested version {}'
+ .format(module_version, version), ImportWarning)
return False


@@ -963,8 +962,7 @@
"""Iterator method."""
if len(self):
return self.popleft()
- else:
- raise StopIteration
+ raise StopIteration


def open_archive(filename, mode='rb', use_extension=True):
@@ -1218,8 +1216,7 @@
and callable(outer_args[0])):
add_decorated_full_name(outer_args[0])
return obj(outer_args[0])
- else:
- return inner_wrapper
+ return inner_wrapper

if not __debug__:
return obj
diff --git a/pywikibot/tools/formatter.py b/pywikibot/tools/formatter.py
index 8c024b8..a893dbd 100644
--- a/pywikibot/tools/formatter.py
+++ b/pywikibot/tools/formatter.py
@@ -71,8 +71,7 @@
"""Get value, filling in 'color' when it is a valid color."""
if key == 'color' and kwargs.get('color') in self.colors:
return '\03{{{0}}}'.format(kwargs[key])
- else:
- return super().get_value(key, args, kwargs)
+ return super().get_value(key, args, kwargs)

def parse(self, format_string: str):
"""Yield results similar to parse but skip colors."""
diff --git a/pywikibot/userinterfaces/terminal_interface_base.py b/pywikibot/userinterfaces/terminal_interface_base.py
index 82567cf..05eaff0 100755
--- a/pywikibot/userinterfaces/terminal_interface_base.py
+++ b/pywikibot/userinterfaces/terminal_interface_base.py
@@ -517,5 +517,4 @@
"""Return true if the level is below or equal to the set level."""
if self.level:
return record.levelno <= self.level
- else:
- return True
+ return True
diff --git a/pywikibot/userinterfaces/transliteration.py b/pywikibot/userinterfaces/transliteration.py
index 6db5b58..158f6ae 100644
--- a/pywikibot/userinterfaces/transliteration.py
+++ b/pywikibot/userinterfaces/transliteration.py
@@ -1134,6 +1134,5 @@
if char == 'ຫ':
if next in 'ງຍນຣລຼຼວ':
return ''
- else:
- return 'h'
+ return 'h'
return default
diff --git a/scripts/add_text.py b/scripts/add_text.py
index 1a25359..e02dab1 100755
--- a/scripts/add_text.py
+++ b/scripts/add_text.py
@@ -130,9 +130,8 @@
pywikibot.output('Server Error! Wait..')
pywikibot.sleep(config.retry_wait)
return None
- else:
- raise pywikibot.ServerError(
- 'Server Error! Maximum retries exceeded')
+ raise pywikibot.ServerError(
+ 'Server Error! Maximum retries exceeded')
except pywikibot.SpamblacklistError as e:
pywikibot.output(
'Cannot change {} because of blacklist entry {}'
diff --git a/scripts/archive/casechecker.py b/scripts/archive/casechecker.py
index 144f35a..a21e9ee 100755
--- a/scripts/archive/casechecker.py
+++ b/scripts/archive/casechecker.py
@@ -638,8 +638,7 @@
"""Colorize code word."""
if not toScreen:
return self._ColorCodeWordHtml(word)
- else:
- return self._ColorCodeWordScreen(word)
+ return self._ColorCodeWordScreen(word)

def _ColorCodeWordHtml(self, word):
res = '<b>'
diff --git a/scripts/archive/commonscat.py b/scripts/archive/commonscat.py
index 951245c..4af2458 100755
--- a/scripts/archive/commonscat.py
+++ b/scripts/archive/commonscat.py
@@ -465,7 +465,7 @@
if m:
if m.group('newcat1'):
return self.checkCommonscatLink(m.group('newcat1'))
- elif m.group('newcat2'):
+ if m.group('newcat2'):
return self.checkCommonscatLink(m.group('newcat2'))
else:
pywikibot.output(
diff --git a/scripts/archive/flickrripper.py b/scripts/archive/flickrripper.py
index bf845b5..758b77c 100755
--- a/scripts/archive/flickrripper.py
+++ b/scripts/archive/flickrripper.py
@@ -404,8 +404,7 @@
if photo.attrib['id'] == end_id:
pywikibot.output('Found end_id')
return
- else:
- yield photo.attrib['id']
+ yield photo.attrib['id']
except flickrapi.exceptions.FlickrError:
gotPhotos = False
pywikibot.output('Flickr api problem, sleeping')
diff --git a/scripts/archive/imageuncat.py b/scripts/archive/imageuncat.py
index c5a78d8..d9b95ce 100755
--- a/scripts/archive/imageuncat.py
+++ b/scripts/archive/imageuncat.py
@@ -1279,7 +1279,7 @@
# Already tagged with a template, skip it
pywikibot.output('Already tagged, skip it')
return False
- elif template in ignoreTemplates:
+ if template in ignoreTemplates:
# template not relevant for categorization
pywikibot.output('Ignore ' + template)
else:
diff --git a/scripts/archive/interwiki.py b/scripts/archive/interwiki.py
index 5a8ed00..f6a7fb9 100755
--- a/scripts/archive/interwiki.py
+++ b/scripts/archive/interwiki.py
@@ -1437,7 +1437,7 @@
StandardOption('give up', 'g')))
if answer == 'g':
return None
- elif answer != 'n':
+ if answer != 'n':
result[site] = answer[1]

# Loop over the ones that have one solution, so are in principle
@@ -1767,7 +1767,7 @@
if answer == 'b':
pywikibot.bot.open_webbrowser(page)
return True
- elif answer == 'a':
+ if answer == 'a':
# don't ask for the rest of this subject
self.conf.always = True
answer = 'y'
diff --git a/scripts/archive/lonelypages.py b/scripts/archive/lonelypages.py
index 103339b..bc4634c 100755
--- a/scripts/archive/lonelypages.py
+++ b/scripts/archive/lonelypages.py
@@ -184,43 +184,42 @@
pywikibot.output("{0} isn't orphan! Skip..."
.format(page.title()))
return
+ # no refs, no redirect; check if there's already the template
+ try:
+ oldtxt = page.get()
+ except pywikibot.NoPage:
+ pywikibot.output("{0} doesn't exist! Skip..."
+ .format(page.title()))
+ return
+ except pywikibot.IsRedirectPage:
+ pywikibot.output('{0} is a redirect! Skip...'
+ .format(page.title()))
+ return
+ if self.settings.regex.search(oldtxt):
+ pywikibot.output(
+ 'Your regex has found something in {0}, skipping...'
+ .format(page.title()))
+ return
+ if (page.isDisambig()
+ and self.opt.disambigPage is not None):
+ pywikibot.output('{0} is a disambig page, report..'
+ .format(page.title()))
+ if not page.title().lower() in self.disambigtext.lower():
+ self.disambigtext = '{0}\n*[[{1}]]'.format(
+ self.disambigtext, page.title())
+ self.disambigpage.text = self.disambigtext
+ self.disambigpage.save(self.commentdisambig)
+ return
+ # Is the page a disambig but there's not disambigPage? Skip!
+ elif page.isDisambig():
+ pywikibot.output('{0} is a disambig page, skip...'
+ .format(page.title()))
+ return
else:
- # no refs, no redirect; check if there's already the template
- try:
- oldtxt = page.get()
- except pywikibot.NoPage:
- pywikibot.output("{0} doesn't exist! Skip..."
- .format(page.title()))
- return
- except pywikibot.IsRedirectPage:
- pywikibot.output('{0} is a redirect! Skip...'
- .format(page.title()))
- return
- if self.settings.regex.search(oldtxt):
- pywikibot.output(
- 'Your regex has found something in {0}, skipping...'
- .format(page.title()))
- return
- if (page.isDisambig()
- and self.opt.disambigPage is not None):
- pywikibot.output('{0} is a disambig page, report..'
- .format(page.title()))
- if not page.title().lower() in self.disambigtext.lower():
- self.disambigtext = '{0}\n*[[{1}]]'.format(
- self.disambigtext, page.title())
- self.disambigpage.text = self.disambigtext
- self.disambigpage.save(self.commentdisambig)
- return
- # Is the page a disambig but there's not disambigPage? Skip!
- elif page.isDisambig():
- pywikibot.output('{0} is a disambig page, skip...'
- .format(page.title()))
- return
- else:
- # Ok, the page need the template. Let's put it there!
- # Adding the template in the text
- newtxt = '{0}\n{1}'.format(self.settings.template, oldtxt)
- self.userPut(page, oldtxt, newtxt, summary=self.comment)
+ # Ok, the page need the template. Let's put it there!
+ # Adding the template in the text
+ newtxt = '{0}\n{1}'.format(self.settings.template, oldtxt)
+ self.userPut(page, oldtxt, newtxt, summary=self.comment)


def main(*args):
diff --git a/scripts/archive/match_images.py b/scripts/archive/match_images.py
index 2f63593..1fe1b14 100755
--- a/scripts/archive/match_images.py
+++ b/scripts/archive/match_images.py
@@ -100,9 +100,8 @@
if averageScore > 0.8:
pywikibot.output('We have a match!')
return True
- else:
- pywikibot.output('Not the same.')
- return False
+ pywikibot.output('Not the same.')
+ return False


def get_image_from_image_page(imagePage):
diff --git a/scripts/archive/nowcommons.py b/scripts/archive/nowcommons.py
index e328d51..556ccd3 100755
--- a/scripts/archive/nowcommons.py
+++ b/scripts/archive/nowcommons.py
@@ -202,8 +202,7 @@
"""Return nowcommons templates."""
if self.site.lang in nowCommons:
return nowCommons[self.site.lang]
- else:
- return nowCommons['_default']
+ return nowCommons['_default']

@property
def nc_templates(self):
diff --git a/scripts/archive/spamremove.py b/scripts/archive/spamremove.py
index fc4be64..3d4be1e 100755
--- a/scripts/archive/spamremove.py
+++ b/scripts/archive/spamremove.py
@@ -103,7 +103,7 @@
'n', automatic_quit=False)
if answer == 'n':
return
- elif answer == 'e':
+ if answer == 'e':
editor = TextEditor()
newtext = editor.edit(text, highlight=self.spam_external_url,
jumpIndex=text.find(self.spam_external_url))
diff --git a/scripts/archivebot.py b/scripts/archivebot.py
index 2e02e3c..69ae930 100755
--- a/scripts/archivebot.py
+++ b/scripts/archivebot.py
@@ -177,8 +177,7 @@
# replace plural variants
exp = i18n.translate(site.code, template, {'$1': int(duration)})
return exp.replace('$1', to_local_digits(duration, site.code))
- else:
- return to_local_digits(string, site.code)
+ return to_local_digits(string, site.code)


def str2time(string: str, timestamp=None) -> datetime.timedelta:
@@ -216,8 +215,7 @@
if timestamp:
return apply_month_delta(
timestamp.date(), month_delta=duration) - timestamp.date()
- else:
- return datetime.timedelta(days=days)
+ return datetime.timedelta(days=days)


def checkstr(string: str) -> Tuple[str, str]:
@@ -742,8 +740,7 @@
for i in sorted(keep_threads)]
self.set_attr('counter', str(counter))
return whys
- else:
- return set()
+ return set()

def run(self) -> None:
"""Process a single DiscussionPage object."""
diff --git a/scripts/category.py b/scripts/category.py
index e5876f9..15933e2 100755
--- a/scripts/category.py
+++ b/scripts/category.py
@@ -335,12 +335,11 @@
# if we already know which subcategories exist here
if supercat in self.catContentDB:
return self.catContentDB[supercat][0]
- else:
- subcatset = set(supercat.subcategories())
- articleset = set(supercat.articles())
- # add to dictionary
- self.catContentDB[supercat] = (subcatset, articleset)
- return subcatset
+ subcatset = set(supercat.subcategories())
+ articleset = set(supercat.articles())
+ # add to dictionary
+ self.catContentDB[supercat] = (subcatset, articleset)
+ return subcatset

def getArticles(self, cat) -> Set[pywikibot.Page]:
"""Return the list of pages for a given category.
@@ -352,12 +351,11 @@
# if we already know which articles exist here.
if cat in self.catContentDB:
return self.catContentDB[cat][1]
- else:
- subcatset = set(cat.subcategories())
- articleset = set(cat.articles())
- # add to dictionary
- self.catContentDB[cat] = (subcatset, articleset)
- return articleset
+ subcatset = set(cat.subcategories())
+ articleset = set(cat.articles())
+ # add to dictionary
+ self.catContentDB[cat] = (subcatset, articleset)
+ return articleset

def getSupercats(self, subcat) -> Set[pywikibot.Category]:
"""Return the supercategory (or a set of) for a given subcategory."""
@@ -365,11 +363,10 @@
# if we already know which subcategories exist here.
if subcat in self.superclassDB:
return self.superclassDB[subcat]
- else:
- supercatset = set(subcat.categories())
- # add to dictionary
- self.superclassDB[subcat] = supercatset
- return supercatset
+ supercatset = set(subcat.categories())
+ # add to dictionary
+ self.superclassDB[subcat] = supercatset
+ return supercatset

def dump(self, filename=None) -> None:
"""Save the dictionaries to disk if not empty.
@@ -447,8 +444,7 @@
sorted_key = split_string[1] + ', ' + split_string[0]
# give explicit sort key
return pywikibot.Page(site, catlink.title() + '|' + sorted_key)
- else:
- return pywikibot.Page(site, catlink.title())
+ return pywikibot.Page(site, catlink.title())

def treat(self, page) -> None:
"""Process one page."""
diff --git a/scripts/checkimages.py b/scripts/checkimages.py
index 9a10b97..cde33f7 100755
--- a/scripts/checkimages.py
+++ b/scripts/checkimages.py
@@ -1309,9 +1309,8 @@
if skip_number == 1:
pywikibot.output('')
return True
- else:
- pywikibot.output('')
- return False
+ pywikibot.output('')
+ return False

@staticmethod
def wait(generator, wait_time) -> Generator[pywikibot.FilePage, None,
diff --git a/scripts/clean_sandbox.py b/scripts/clean_sandbox.py
index 1fcf8f1..5a00577 100755
--- a/scripts/clean_sandbox.py
+++ b/scripts/clean_sandbox.py
@@ -246,7 +246,7 @@
if self.opt.no_repeat:
pywikibot.output('\nDone.')
return
- elif not wait:
+ if not wait:
if self.opt.hours < 1.0:
pywikibot.output('\nSleeping {} minutes, now {}'.format(
(self.opt.hours * 60), now))
diff --git a/scripts/harvest_template.py b/scripts/harvest_template.py
index d282302..85665c7 100755
--- a/scripts/harvest_template.py
+++ b/scripts/harvest_template.py
@@ -243,8 +243,7 @@
local = handler.opt[option]
if isinstance(default, bool) and isinstance(local, bool):
return default is not local
- else:
- return local or default
+ return local or default

def treat_page_and_item(self, page, item) -> None:
"""Process a single page/item."""
diff --git a/scripts/listpages.py b/scripts/listpages.py
index 4ebb684..4729b26 100755
--- a/scripts/listpages.py
+++ b/scripts/listpages.py
@@ -162,8 +162,7 @@
"Required format code needs 'outputlang' parameter set.")
if num is None:
return fmt.format(page=self)
- else:
- return fmt.format(num=num, page=self)
+ return fmt.format(num=num, page=self)


def main(*args) -> None:
diff --git a/scripts/replace.py b/scripts/replace.py
index 73b8ce5..ea0debb 100755
--- a/scripts/replace.py
+++ b/scripts/replace.py
@@ -353,8 +353,7 @@
"""Return this entry's edit summary or the fix's summary."""
if self._edit_summary is None:
return self.fix_set.edit_summary
- else:
- return self._edit_summary
+ return self._edit_summary

@property
def container(self):
diff --git a/scripts/solve_disambiguation.py b/scripts/solve_disambiguation.py
index 65d6edc..b3c8428 100755
--- a/scripts/solve_disambiguation.py
+++ b/scripts/solve_disambiguation.py
@@ -376,8 +376,7 @@
linklower = first_lower(linkupper)
if '[[%s]]' % linklower in text or '[[%s|' % linklower in text:
return linklower
- else:
- return linkupper
+ return linkupper


class ReferringPageGeneratorWithIgnore:
diff --git a/tests/archive/disambredir_tests.py b/tests/archive/disambredir_tests.py
index bb5eed5..86736a9 100644
--- a/tests/archive/disambredir_tests.py
+++ b/tests/archive/disambredir_tests.py
@@ -50,8 +50,7 @@
answer = callback.handle_answer(choice)
callback._current_match = None
return answer
- else:
- return None
+ return None

callback = original(old, new)
return _patched_callback
diff --git a/tests/aspects.py b/tests/aspects.py
index fc9fb29..6002220 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -1022,9 +1022,8 @@
if hasattr(context, '__enter__'):
return self._delay_assertion(context, assertion, args,
kwargs)
- else:
- self.after_assert(assertion, *args, **kwargs)
- return context
+ self.after_assert(assertion, *args, **kwargs)
+ return context
finally:
self._patched = False
return inner_assert
@@ -1034,8 +1033,7 @@
result = super().__getattribute__(attr)
if attr.startswith('assert') and not self._patched:
return self.patch_assert(result)
- else:
- return result
+ return result


class PatchingTestCase(TestCase):
@@ -1595,8 +1593,7 @@
"""
if hasattr(self, 'httpbin'):
return self.httpbin.url + path
- else:
- return 'http://httpbin.org' + path
+ return 'http://httpbin.org' + path

def get_httpbin_hostname(self):
"""
@@ -1607,5 +1604,4 @@
"""
if hasattr(self, 'httpbin'):
return '{0}:{1}'.format(self.httpbin.host, self.httpbin.port)
- else:
- return 'httpbin.org'
+ return 'httpbin.org'
diff --git a/tests/plural_tests.py b/tests/plural_tests.py
index 5bc8a01..502d7c9 100644
--- a/tests/plural_tests.py
+++ b/tests/plural_tests.py
@@ -43,8 +43,7 @@
# Don't already fail on creation
if callable(rule.get('plural')):
return test_callable_rule
- else:
- return test_static_rule
+ return test_static_rule

for lang, rule in plural.plural_rules.items():
cls.add_method(dct, 'test_{0}'.format(lang.replace('-', '_')),
diff --git a/tests/textlib_tests.py b/tests/textlib_tests.py
index f5fe77d..139cb99 100644
--- a/tests/textlib_tests.py
+++ b/tests/textlib_tests.py
@@ -790,7 +790,7 @@
self.assertEqual(link.site, self.wp_site)
if link.title == 'World':
return pywikibot.Link('Homeworld', link.site)
- elif link.title.lower() == 'you':
+ if link.title.lower() == 'you':
return False
self.assertEqual(
textlib.replace_links(self.text, callback, self.wp_site),
@@ -805,9 +805,8 @@
return pywikibot.Link(
'{0}#{1}'
.format(self._count, link.section), link.site)
- else:
- return pywikibot.Link('{0}'
- .format(self._count), link.site)
+ return pywikibot.Link('{0}'
+ .format(self._count), link.site)
self._count = 0 # buffer number of found instances
self.assertEqual(
textlib.replace_links(self.text, callback, self.wp_site),
diff --git a/tests/utils.py b/tests/utils.py
index 1e14e9f..ef024c5 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -41,8 +41,7 @@
"""
if expect:
return unittest.expectedFailure
- else:
- return lambda orig: orig
+ return lambda orig: orig


def fixed_generator(iterable):

To view, visit change 673587. To unsubscribe, or for help writing mail filters, visit settings.

Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I32cf4ef18183acbb518823f9ae86bf4693f72e5d
Gerrit-Change-Number: 673587
Gerrit-PatchSet: 5
Gerrit-Owner: Zabe <alec@vc-celle.de>
Gerrit-Reviewer: D3r1ck01 <xsavitar.wiki@aol.com>
Gerrit-Reviewer: Isaacandy <isaac@iznd.xyz>
Gerrit-Reviewer: Siebrand <siebrand@kitano.nl>
Gerrit-Reviewer: Xqt <info@gno.de>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged