Skip to content

Commit

Permalink
[IMPR] code improvements
Browse files Browse the repository at this point in the history
raise exception first instead after else condition and decrease nested flow.

Change-Id: I47132f0488b4680ea96e1217be3b7f18b616e385
  • Loading branch information
xqt committed Oct 4, 2024
1 parent 0c6d895 commit e99ca29
Show file tree
Hide file tree
Showing 12 changed files with 75 additions and 76 deletions.
11 changes: 5 additions & 6 deletions pywikibot/comms/eventstreams.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
Server-Sent Events client.
"""Server-Sent Events client.
This file is part of the Pywikibot framework.
Expand All @@ -10,7 +9,7 @@
.. versionadded:: 3.0
"""
#
# (C) Pywikibot team, 2017-2023
# (C) Pywikibot team, 2017-2024
#
# Distributed under the terms of the MIT license.
#
Expand Down Expand Up @@ -281,11 +280,11 @@ def _in(data, key=None, value=None):

# register an external filter function
for func in args:
if callable(func):
self.filter[ftype].append(func)
else:
if not callable(func):
raise TypeError(f'{func} is not a callable')

self.filter[ftype].append(func)

# register pairs of keys and items as a filter function
for key, value in kwargs.items():
# append function for singletons
Expand Down
11 changes: 6 additions & 5 deletions pywikibot/cosmetic_changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,12 +298,13 @@ def safe_execute(self, method: Callable[[str], str], text: str) -> str:
try:
result = method(text)
except Exception as e:
if self.ignore == CANCEL.METHOD:
pywikibot.warning('Unable to perform "{}" on "{}"!'
.format(method.__name__, self.title))
pywikibot.error(e)
else:
if self.ignore != CANCEL.METHOD:
raise

pywikibot.warning(
f'Unable to perform "{method.__name__}" on "{self.title}"!')
pywikibot.error(e)

return text if result is None else result

def _change(self, text: str) -> str:
Expand Down
16 changes: 8 additions & 8 deletions pywikibot/family.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,16 +346,16 @@ def load(fam: str | None = None):
if fam in Family._families:
return Family._families[fam]

if fam in config.family_files:
family_file = config.family_files[fam]

if family_file.startswith(('http://', 'https://')):
myfamily = AutoFamily(fam, family_file)
Family._families[fam] = myfamily
return Family._families[fam]
else:
if fam not in config.family_files:
raise UnknownFamilyError(f'Family {fam} does not exist')

family_file = config.family_files[fam]

if family_file.startswith(('http://', 'https://')):
myfamily = AutoFamily(fam, family_file)
Family._families[fam] = myfamily
return Family._families[fam]

try:
# Ignore warnings due to dots in family names.
# TODO: use more specific filter, so that family classes can use
Expand Down
22 changes: 11 additions & 11 deletions pywikibot/page/_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,18 +160,18 @@ def normalizeData(cls, data: dict) -> dict:
"""
norm_data = {}
for key, values in data.items():
if isinstance(values, list):
strings = []
for value in values:
if isinstance(value, str):
strings.append({'language': key, 'value': value})
else:
strings.append(value)
norm_data[key] = strings
else:
if not isinstance(values, list):
raise TypeError(
"Unsupported value type {!r} for '{}'; list expected."
.format(type(values).__name__, values))
f'Unsupported value type {type(values).__name__!r}'
f"for '{values}'; list expected.")

strings = []
for value in values:
if isinstance(value, str):
strings.append({'language': key, 'value': value})
else:
strings.append(value)
norm_data[key] = strings

return norm_data

Expand Down
5 changes: 3 additions & 2 deletions pywikibot/page/_wikibase.py
Original file line number Diff line number Diff line change
Expand Up @@ -1029,8 +1029,9 @@ def _defined_by(self, singular: bool = False) -> dict:
# if none of the above applies, this item is in an invalid state
# which needs to be raise as an exception, but also logged in case
# an exception handler is catching the generic Error.
pywikibot.error(f'{self.__class__.__name__} is in invalid state')
raise Error(f'{self.__class__.__name__} is in invalid state')
msg = f'{self.__class__.__name__} is in invalid state'
pywikibot.error(msg)
raise Error(msg)

return params

Expand Down
6 changes: 3 additions & 3 deletions pywikibot/pagegenerators/_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,11 +214,11 @@ def upcast(gen):
try:
yield pageclass(site, rc['title'])
except ValueError:
if pageclass == pywikibot.FilePage:
pywikibot.exception()
else:
if pageclass != pywikibot.FilePage:
raise

pywikibot.exception()

if site is None:
site = pywikibot.Site()

Expand Down
25 changes: 12 additions & 13 deletions pywikibot/textlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,16 +193,14 @@ def pattern(self, template, flags=re.DOTALL):
# TODO: merge regex with NESTED_TEMPLATE_REGEX
namespace = self.site.namespaces[10]
if isinstance(template, pywikibot.Page):
if template.namespace() == 10:
old = template.title(with_ns=False)
else:
raise ValueError(
f'{template} is not a template Page object')
if template.namespace() != 10:
raise ValueError(f'{template} is not a template Page object')

old = template.title(with_ns=False)
elif isinstance(template, str):
old = template
else:
raise ValueError(
f'{template!r} is not a valid template')
raise ValueError(f'{template!r} is not a valid template')

pattern = case_escape(namespace.case, old)
# namespaces may be any mixed case
Expand Down Expand Up @@ -1419,13 +1417,14 @@ def interwikiFormat(links: dict, insite=None) -> str:
for site in ar:
if isinstance(links[site], pywikibot.Link):
links[site] = pywikibot.Page(links[site])
if isinstance(links[site], pywikibot.Page):
title = links[site].title(as_link=True, force_interwiki=True,
insite=insite)
link = title.replace('[[:', '[[')
s.append(link)
else:
if not isinstance(links[site], pywikibot.Page):
raise ValueError('links dict must contain Page or Link objects')

title = links[site].title(as_link=True, force_interwiki=True,
insite=insite)
link = title.replace('[[:', '[[')
s.append(link)

sep = ' ' if insite.code in insite.family.interwiki_on_one_line else '\n'
return sep.join(s) + '\n'

Expand Down
14 changes: 7 additions & 7 deletions pywikibot/tools/_deprecate.py
Original file line number Diff line number Diff line change
Expand Up @@ -706,17 +706,17 @@ def add_deprecated_attr(self, name: str, replacement: Any = None, *,
f'Module has already an attribute named "{name}".')

if replacement_name is None:
if hasattr(replacement, '__name__'):
replacement_name = replacement.__module__
if hasattr(replacement, '__self__'):
replacement_name += '.'
replacement_name += replacement.__self__.__class__.__name__
replacement_name += '.' + replacement.__name__
else:
if not hasattr(replacement, '__name__'):
raise TypeError('Replacement must have a __name__ attribute '
'or a replacement name must be set '
'specifically.')

replacement_name = replacement.__module__
if hasattr(replacement, '__self__'):
replacement_name += '.'
replacement_name += replacement.__self__.__class__.__name__
replacement_name += '.' + replacement.__name__

if not warning_message:
warning_message = _build_msg_string(
replacement_name, since).format('{0}.{1}', '{2}')
Expand Down
20 changes: 10 additions & 10 deletions scripts/archivebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,18 +678,18 @@ def analyze_page(self) -> set[tuple[str, str]]:
try:
key = pattern % params
except TypeError as e:
if 'a real number is required' in str(e):
pywikibot.error(e)
pywikibot.info(
fill('<<lightblue>>Use string format field like '
'%(localfield)s instead of %(localfield)d. '
'Trying to solve it...'))
pywikibot.info()
pattern = stringpattern
key = pattern % params
else:
if 'a real number is required' not in str(e):
raise MalformedConfigError(e)

pywikibot.error(e)
pywikibot.info(
fill('<<lightblue>>Use string format field like '
'%(localfield)s instead of %(localfield)d. '
'Trying to solve it...'))
pywikibot.info()
pattern = stringpattern
key = pattern % params

threads_per_archive[key].append((i, thread))
whys.add(why) # FIXME: we don't know if we ever archive anything

Expand Down
10 changes: 5 additions & 5 deletions scripts/harvest_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,13 @@

def _signal_handler(signum, frame) -> None:
global willstop
if not willstop:
willstop = True
pywikibot.info('Received ctrl-c. Finishing current item; '
'press ctrl-c again to abort.')
else:
if willstop:
raise KeyboardInterrupt

willstop = True
pywikibot.info('Received ctrl-c. Finishing current item; '
'press ctrl-c again to abort.')


signal.signal(signal.SIGINT, _signal_handler)

Expand Down
5 changes: 2 additions & 3 deletions scripts/unusedfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,9 @@ def append_text(self, page, apptext):
if page.exists():
text = page.text
else:
if page.isTalkPage():
text = ''
else:
if not page.isTalkPage():
raise NoPageError(page)
text = ''

text += apptext
self.current_page = page
Expand Down
6 changes: 3 additions & 3 deletions tests/aspects.py
Original file line number Diff line number Diff line change
Expand Up @@ -964,12 +964,12 @@ def get_site(cls, name=None):
*name*.
"""
if not name and hasattr(cls, 'sites'):
if len(cls.sites) == 1:
name = next(iter(cls.sites.keys()))
else:
if len(cls.sites) != 1:
raise Exception(f'"{cls.__name__}.get_site(name=None)"'
' called with multiple sites')

name = next(iter(cls.sites.keys()))

if name and name not in cls.sites:
raise Exception(f'"{name}" not declared in {cls.__name__}')

Expand Down

0 comments on commit e99ca29

Please sign in to comment.