jenkins-bot has submitted this change. ( 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1077983?usp=email )

Change subject: [IMPR] code improvements
......................................................................

[IMPR] code improvements

raise exception first instead after else condition and decrease nested flow.

Change-Id: I47132f0488b4680ea96e1217be3b7f18b616e385
---
M pywikibot/comms/eventstreams.py
M pywikibot/cosmetic_changes.py
M pywikibot/family.py
M pywikibot/page/_collections.py
M pywikibot/page/_wikibase.py
M pywikibot/pagegenerators/_generators.py
M pywikibot/textlib.py
M pywikibot/tools/_deprecate.py
M scripts/archivebot.py
M scripts/harvest_template.py
M scripts/unusedfiles.py
M tests/aspects.py
12 files changed, 75 insertions(+), 76 deletions(-)

Approvals:
  Xqt: Looks good to me, approved
  jenkins-bot: Verified




diff --git a/pywikibot/comms/eventstreams.py b/pywikibot/comms/eventstreams.py
index 8618b87..5bc6530 100644
--- a/pywikibot/comms/eventstreams.py
+++ b/pywikibot/comms/eventstreams.py
@@ -1,5 +1,4 @@
-"""
-Server-Sent Events client.
+"""Server-Sent Events client.

 This file is part of the Pywikibot framework.

@@ -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.
 #
@@ -281,11 +280,11 @@

         # 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
diff --git a/pywikibot/cosmetic_changes.py b/pywikibot/cosmetic_changes.py
index 2a17aa5..8df7cd4 100644
--- a/pywikibot/cosmetic_changes.py
+++ b/pywikibot/cosmetic_changes.py
@@ -298,12 +298,13 @@
         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:
diff --git a/pywikibot/family.py b/pywikibot/family.py
index 26cd685..6cb4ece 100644
--- a/pywikibot/family.py
+++ b/pywikibot/family.py
@@ -346,16 +346,16 @@
         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
diff --git a/pywikibot/page/_collections.py b/pywikibot/page/_collections.py
index 1abf430..ee0edeb 100644
--- a/pywikibot/page/_collections.py
+++ b/pywikibot/page/_collections.py
@@ -160,18 +160,18 @@
         """
         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

diff --git a/pywikibot/page/_wikibase.py b/pywikibot/page/_wikibase.py
index 8806e2c..afb189b 100644
--- a/pywikibot/page/_wikibase.py
+++ b/pywikibot/page/_wikibase.py
@@ -1029,8 +1029,9 @@
             # 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

diff --git a/pywikibot/pagegenerators/_generators.py 
b/pywikibot/pagegenerators/_generators.py
index a7239e2..2956b35 100644
--- a/pywikibot/pagegenerators/_generators.py
+++ b/pywikibot/pagegenerators/_generators.py
@@ -214,11 +214,11 @@
             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()

diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py
index af64ff7..4ab11ca 100644
--- a/pywikibot/textlib.py
+++ b/pywikibot/textlib.py
@@ -193,16 +193,14 @@
         # 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
@@ -1419,13 +1417,14 @@
     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'

diff --git a/pywikibot/tools/_deprecate.py b/pywikibot/tools/_deprecate.py
index c87a964..bff2a18 100644
--- a/pywikibot/tools/_deprecate.py
+++ b/pywikibot/tools/_deprecate.py
@@ -706,17 +706,17 @@
                 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}')
diff --git a/scripts/archivebot.py b/scripts/archivebot.py
index 7745ff9..8694d64 100755
--- a/scripts/archivebot.py
+++ b/scripts/archivebot.py
@@ -678,18 +678,18 @@
             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

diff --git a/scripts/harvest_template.py b/scripts/harvest_template.py
index 6c89c49..e495cc2 100755
--- a/scripts/harvest_template.py
+++ b/scripts/harvest_template.py
@@ -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)

diff --git a/scripts/unusedfiles.py b/scripts/unusedfiles.py
index 68c194b..aa885e1 100755
--- a/scripts/unusedfiles.py
+++ b/scripts/unusedfiles.py
@@ -150,10 +150,9 @@
         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
diff --git a/tests/aspects.py b/tests/aspects.py
index 769214f..67d5bad 100644
--- a/tests/aspects.py
+++ b/tests/aspects.py
@@ -964,12 +964,12 @@
             *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__}')


--
To view, visit 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1077983?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: I47132f0488b4680ea96e1217be3b7f18b616e385
Gerrit-Change-Number: 1077983
Gerrit-PatchSet: 2
Gerrit-Owner: Xqt <i...@gno.de>
Gerrit-Reviewer: D3r1ck01 <dalangi-...@wikimedia.org>
Gerrit-Reviewer: Xqt <i...@gno.de>
Gerrit-Reviewer: jenkins-bot
_______________________________________________
Pywikibot-commits mailing list -- pywikibot-commits@lists.wikimedia.org
To unsubscribe send an email to pywikibot-commits-le...@lists.wikimedia.org

Reply via email to