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

Change subject: Typing: Solve some mypy issues
......................................................................

Typing: Solve some mypy issues

Note: | operator for union types is available with Python 3.10
MyPy test are made with Python 3.9

Change-Id: I17facfd8d6697abd075695852d95cc1398865abf
---
M .pre-commit-config.yaml
M conftest.py
M pyproject.toml
M pywikibot/_wbtypes.py
M pywikibot/bot.py
M pywikibot/data/wikistats.py
M pywikibot/date.py
M pywikibot/i18n.py
M pywikibot/page/_wikibase.py
M pywikibot/plural.py
M pywikibot/site/_namespace.py
11 files changed, 74 insertions(+), 36 deletions(-)

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




diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 1560236..10a958f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -126,12 +126,12 @@
         # They should be also used in conftest.py to exclude them from 
non-voting mypy test.
         files: |
           (?x)^pywikibot/(
-            
(__metadata__|backports|config|diff|echo|exceptions|fixes|logging|time)|
+            
(__metadata__|backports|config|diff|echo|exceptions|fixes|logging|plural|time)|
             (comms|data|families|specialbots)/__init__|
             comms/eventstreams|
-            data/(api/(__init__|_optionset)|memento)|
+            data/(api/(__init__|_optionset)|memento|wikistats)|
             families/[a-z][a-z\d]+_family|
-            page/(__init__|_decorators|_revision)|
+            page/(__init__|_decorators|_page|_revision)|
             pagegenerators/(__init__|_filters)|
             scripts/(?:i18n/)?__init__|
             
site/(__init__|_basesite|_decorators|_interwikimap|_tokenwallet|_upload)|
diff --git a/conftest.py b/conftest.py
index 0155796..e33738a 100644
--- a/conftest.py
+++ b/conftest.py
@@ -16,12 +16,13 @@

 EXCLUDE_PATTERN = re.compile(
     r'(?:'
-    r'(__metadata__|backports|config|diff|echo|exceptions|fixes|logging|time)|'
+    r'(__metadata__|backports|config|diff|echo|exceptions|fixes|logging|'
+    r'plural|time)|'
     r'(comms|data|families|specialbots)/__init__|'
     r'comms/eventstreams|'
-    r'data/(api/(__init__|_optionset)|memento)|'
+    r'data/(api/(__init__|_optionset)|memento|wikistats)|'
     r'families/[a-z][a-z\d]+_family|'
-    r'page/(__init__|_decorators|_revision)|'
+    r'page/(__init__|_decorators|_page|_revision)|'
     r'pagegenerators/(__init__|_filters)|'
     r'scripts/(i18n/)?__init__|'
     r'site/(__init__|_basesite|_decorators|_interwikimap|'
diff --git a/pyproject.toml b/pyproject.toml
index 3f3e66a..d37f51c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -187,7 +187,7 @@


 [tool.mypy]
-python_version = 3.9
+python_version = "3.9"
 enable_error_code = [
     "ignore-without-code",
 ]
diff --git a/pywikibot/_wbtypes.py b/pywikibot/_wbtypes.py
index 0aa2317..3713931 100644
--- a/pywikibot/_wbtypes.py
+++ b/pywikibot/_wbtypes.py
@@ -28,10 +28,12 @@


 if TYPE_CHECKING:
+    from typing import Union, cast
+
     from pywikibot.site import APISite, BaseSite, DataSite

-    ItemPageStrNoneType = str | pywikibot.ItemPage | None
-    ToDecimalType = int | float | str | Decimal | None
+    ItemPageStrNoneType = Union[str, pywikibot.ItemPage, None]
+    ToDecimalType = Union[int, float, str, Decimal, None]


 __all__ = (
@@ -49,6 +51,8 @@

     """Abstract class for Wikibase representations."""

+    _items: tuple[str, ...]
+
     @abc.abstractmethod
     def __init__(self) -> None:
         """Initializer."""
@@ -379,7 +383,7 @@

         return self.PRECISION[key]

-    def __iter__(self) -> Iterator[int]:
+    def __iter__(self) -> Iterator[str]:
         return iter(self.PRECISION)

     def __len__(self) -> int:
@@ -401,6 +405,12 @@
     :class:`pywikibot.Timestamp` and :meth:`fromTimestamp`.
     """

+    month: int
+    day: int
+    hour: int
+    minute: int
+    second: int
+
     PRECISION = _Precision()

     FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'
@@ -529,8 +539,8 @@
             if (isinstance(precision, int)
                     and precision in self.PRECISION.values()):
                 prec = precision
-            elif precision in self.PRECISION:
-                prec = self.PRECISION[precision]
+            elif isinstance(precision, str) and precision in self.PRECISION:
+                prec = self.PRECISION[cast(str, precision)]
             else:
                 raise ValueError(f'Invalid precision: "{precision}"')

diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index d3457ae..b197307 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -190,9 +190,11 @@


 if TYPE_CHECKING:
+    from typing import Union
+
     from pywikibot.site import BaseSite

-    AnswerType = Iterable[tuple[str, str] | Option] | Option
+    AnswerType = Union[Iterable[Union[tuple[str, str], Option]], Option]

 _GLOBAL_HELP = """
 GLOBAL OPTIONS
diff --git a/pywikibot/data/wikistats.py b/pywikibot/data/wikistats.py
index d85a371..e3570cf 100644
--- a/pywikibot/data/wikistats.py
+++ b/pywikibot/data/wikistats.py
@@ -1,6 +1,6 @@
 """Objects representing WikiStats API."""
 #
-# (C) Pywikibot team, 2014-2024
+# (C) Pywikibot team, 2014-2025
 #
 # Distributed under the terms of the MIT license.
 #
@@ -122,10 +122,10 @@
             alphanumeric keys are sorted in normal way.
         :return: The sorted table
         """
-        table = self.get(table)
+        data = self.get(table)

         # take the first entry to determine the sorting key
-        first_entry = table[0]
+        first_entry = data[0]
         if first_entry[key].isdigit():
             def sort_key(d): return int(d[key])
             reverse = reverse if reverse is not None else True
@@ -133,7 +133,7 @@
             def sort_key(d): return d[key]
             reverse = reverse if reverse is not None else False

-        return sorted(table, key=sort_key, reverse=reverse)
+        return sorted(data, key=sort_key, reverse=reverse)

     def languages_by_size(self, table: str):
         """Return ordered list of languages by size from WikiStats."""
diff --git a/pywikibot/date.py b/pywikibot/date.py
index 9c2a01e..886efeb 100644
--- a/pywikibot/date.py
+++ b/pywikibot/date.py
@@ -30,16 +30,17 @@


 if TYPE_CHECKING:
-    tuplst_type = list[tuple[Callable[[int | str], Any],
-                             Callable[[int | str], bool]]]
-    encf_type = Callable[[int], int | Sequence[int]]
+    from typing import Union
+    tuplst_type = list[tuple[Callable[[Union[int, str]], Any],
+                             Callable[[Union[int, str]], bool]]]
+    encf_type = Callable[[int], Union[int, Sequence[int]]]
     decf_type = Callable[[Sequence[int]], int]
     # decoders are three value tuples, with an optional fourth to represent a
     # required number of digits
-    decoder_type = (
-        tuple[str, Callable[[int], str], Callable[[str], int]]
-        | tuple[str, Callable[[int], str], Callable[[str], int], int]
-    )
+    decoder_type = Union[
+        tuple[str, Callable[[int], str], Callable[[str], int]],
+        tuple[str, Callable[[int], str], Callable[[str], int], int]
+    ]

 #
 # Different collections of well known formats
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py
index a7f17de..62d5b27 100644
--- a/pywikibot/i18n.py
+++ b/pywikibot/i18n.py
@@ -29,6 +29,7 @@
 from contextlib import suppress
 from pathlib import Path
 from textwrap import fill
+from typing import Any

 import pywikibot
 from pywikibot import __url__, config
@@ -554,9 +555,9 @@
 

 def translate(code: str | pywikibot.site.BaseSite,
-              xdict: str | Mapping[str, str],
+              xdict: str | Mapping[str, Any],
               parameters: Mapping[str, int] | None = None,
-              fallback: bool | Iterable[str] = False) -> str | None:
+              fallback: bool | Iterable[str] = False) -> Any | None:
     """Return the most appropriate localization from a localization dict.

     Given a site code and a dictionary, returns the dictionary's value
@@ -591,7 +592,7 @@
     :param parameters: For passing (plural) parameters
     :param fallback: Try an alternate language code. If it's iterable
         it'll also try those entries and choose the first match.
-    :return: the localized string
+    :return: the localized value, usually a string
     :raise IndexError: If the language supports and requires more
         plurals than defined for the given PLURAL pattern.
     :raise KeyError: No fallback key found if fallback is not False
diff --git a/pywikibot/page/_wikibase.py b/pywikibot/page/_wikibase.py
index b328e45..1ef035b 100644
--- a/pywikibot/page/_wikibase.py
+++ b/pywikibot/page/_wikibase.py
@@ -64,15 +64,17 @@
 )

 if TYPE_CHECKING:
-    LANGUAGE_IDENTIFIER = str | pywikibot.site.APISite
+    from typing import Union
+    LANGUAGE_IDENTIFIER = Union[str, pywikibot.site.APISite]
     ALIASES_TYPE = dict[LANGUAGE_IDENTIFIER, list[str]]
     LANGUAGE_TYPE = dict[LANGUAGE_IDENTIFIER, str]
-    SITELINK_TYPE = (
-        pywikibot.page.BasePage
-        | pywikibot.page.BaseLink
-        | dict[str, str]
-    )
-    ENTITY_DATA_TYPE = dict[str, LANGUAGE_TYPE | ALIASES_TYPE | SITELINK_TYPE]
+    SITELINK_TYPE = Union[
+        pywikibot.page.BasePage,
+        pywikibot.page.BaseLink,
+        dict[str, str]
+    ]
+    ENTITY_DATA_TYPE = dict[str,
+                            Union[LANGUAGE_TYPE, ALIASES_TYPE, SITELINK_TYPE]]


 class WikibaseEntity:
diff --git a/pywikibot/plural.py b/pywikibot/plural.py
index 8fb0e54..d353bcf 100644
--- a/pywikibot/plural.py
+++ b/pywikibot/plural.py
@@ -6,11 +6,12 @@
 #
 from __future__ import annotations

-from typing import TYPE_CHECKING, Callable
+from typing import TYPE_CHECKING


 if TYPE_CHECKING:
-    PluralRule = dict[str, int | Callable[[int], bool | int]]
+    from typing import Callable, Union
+    PluralRule = dict[str, Union[int, Callable[[int], Union[bool, int]]]]

 plural_rules: dict[str, PluralRule] = {
     '_default': {'nplurals': 2, 'plural': lambda n: (n != 1)},
diff --git a/pywikibot/site/_namespace.py b/pywikibot/site/_namespace.py
index f82c03b..e28fd55 100644
--- a/pywikibot/site/_namespace.py
+++ b/pywikibot/site/_namespace.py
@@ -91,6 +91,26 @@
        metaclass from :class:`MetaNamespace`
     """

+    # Hints of BuiltinNamespace types added with initializer
+    MEDIA: int
+    SPECIAL: int
+    MAIN: int
+    TALK: int
+    USER: int
+    USER_TALK: int
+    PROJECT: int
+    PROJECT_TALK: int
+    FILE: int
+    FILE_TALK: int
+    MEDIAWIKI: int
+    MEDIAWIKI_TALK: int
+    TEMPLATE: int
+    TEMPLATE_TALK: int
+    HELP: int
+    HELP_TALK: int
+    CATEGORY: int
+    CATEGORY_TALK: int
+
     def __init__(self, id,
                  canonical_name: str | None = None,
                  custom_name: str | None = None,

--
To view, visit 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1190739?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: I17facfd8d6697abd075695852d95cc1398865abf
Gerrit-Change-Number: 1190739
Gerrit-PatchSet: 5
Gerrit-Owner: Xqt <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
_______________________________________________
Pywikibot-commits mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to