Xqt has submitted this change. ( 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1200451?usp=email )

Change subject: cleanup: replace Pattern, Match from backports with re.Pattern, 
re.Match
......................................................................

cleanup: replace Pattern, Match from backports with re.Pattern, re.Match

Bug: T401802
Change-Id: I70eaa7d5394fe00789ca3023e2176e237d633183
---
M pywikibot/backports.py
M pywikibot/cosmetic_changes.py
M pywikibot/data/api/_requests.py
M pywikibot/date.py
M pywikibot/i18n.py
M pywikibot/pagegenerators/_filters.py
M pywikibot/site/_apisite.py
M pywikibot/site/_basesite.py
M pywikibot/textlib.py
M scripts/archivebot.py
M scripts/replace.py
11 files changed, 42 insertions(+), 54 deletions(-)

Approvals:
  Xqt: Verified; Looks good to me, approved




diff --git a/pywikibot/backports.py b/pywikibot/backports.py
index 3734d80..8ece3db 100644
--- a/pywikibot/backports.py
+++ b/pywikibot/backports.py
@@ -45,8 +45,6 @@
         Iterable,
         Iterator,
         Mapping,
-        Match,
-        Pattern,
         Sequence,
     )
 else:
@@ -59,7 +57,6 @@
         Mapping,
         Sequence,
     )
-    from re import Match, Pattern

 if PYTHON_VERSION < (3, 9, 2):
     from typing import Callable
diff --git a/pywikibot/cosmetic_changes.py b/pywikibot/cosmetic_changes.py
index 725a924..0781976 100644
--- a/pywikibot/cosmetic_changes.py
+++ b/pywikibot/cosmetic_changes.py
@@ -64,7 +64,7 @@

 import pywikibot
 from pywikibot import exceptions, i18n, textlib
-from pywikibot.backports import Callable, Match, Pattern
+from pywikibot.backports import Callable
 from pywikibot.site import Namespace
 from pywikibot.tools import first_lower, first_upper
 from pywikibot.tools.chars import url2string
@@ -199,7 +199,7 @@
     MATCH = 3


-def _format_isbn_match(match: Match[str], *, strict: bool = True) -> str:
+def _format_isbn_match(match: re.Match[str], *, strict: bool = True) -> str:
     """Helper function to validate and format a single matched ISBN."""
     if not stdnum_isbn:
         raise NotImplementedError(
@@ -501,7 +501,7 @@
             if not cache:
                 cache[False] = True  # signal there is nothing to replace

-        def replace_magicword(match: Match[str]) -> str:
+        def replace_magicword(match: re.Match[str]) -> str:
             """Replace magic words in file link params, leaving captions."""
             linktext = match.group()
             if cache.get(False):
@@ -522,7 +522,7 @@
             replaced = '|'.join(cache.get(p.strip(), p) for p in parts)

             # extract namespace
-            m = cast(Match[str],
+            m = cast(re.Match[str],
                      re.match(r'\[\[\s*(?P<namespace>[^:]+)\s*:', linktext))

             return f'[[{m["namespace"]}:{match["filename"]}{replaced}]]'
@@ -555,7 +555,7 @@
         """
         # helper function which works on one link and either returns it
         # unmodified, or returns a replacement.
-        def handleOneLink(match: Match[str]) -> str:
+        def handleOneLink(match: re.Match[str]) -> str:
             # Convert URL-encoded characters to str
             titleWithSection = url2string(match['titleWithSection'],
                                           encodings=self.site.encodings())
@@ -841,7 +841,7 @@
     # from fixes.py
     def fixSyntaxSave(self, text: str) -> str:
         """Convert weblinks to wikilink, fix link syntax."""
-        def replace_link(match: Match[str]) -> str:
+        def replace_link(match: re.Match[str]) -> str:
             """Create a string to replace a single link."""
             replacement = '[['
             if re.match(
@@ -927,7 +927,7 @@

     def fixHtml(self, text: str) -> str:
         """Replace html markups with wikitext markups."""
-        def replace_header(match: Match[str]) -> str:
+        def replace_header(match: re.Match[str]) -> str:
             """Create a header string for replacing."""
             depth = int(match[1])
             return r'{0} {1} {0}'.format('=' * depth, match[2])
@@ -987,7 +987,7 @@

     def fixTypo(self, text: str) -> str:
         """Fix units."""
-        exceptions: list[str | Pattern[str]] = [
+        exceptions: list[str | re.Pattern[str]] = [
             'comment',
             'gallery',
             'hyperlink',
@@ -1021,7 +1021,7 @@
         if self.site.code not in ['ckb', 'fa']:
             return text

-        exceptions: list[str | Pattern[str]] = [
+        exceptions: list[str | re.Pattern[str]] = [
             'file',
             'gallery',
             'hyperlink',
diff --git a/pywikibot/data/api/_requests.py b/pywikibot/data/api/_requests.py
index 26ed60a..28361c1 100644
--- a/pywikibot/data/api/_requests.py
+++ b/pywikibot/data/api/_requests.py
@@ -25,7 +25,7 @@

 import pywikibot
 from pywikibot import config
-from pywikibot.backports import Callable, Match
+from pywikibot.backports import Callable
 from pywikibot.comms import http
 from pywikibot.data import WaitingMixin
 from pywikibot.exceptions import (
@@ -239,7 +239,8 @@
             raise ValueError("'action' specification missing from Request.")
         self.action = parameters['action']
         self.update(parameters)  # also convert all parameter values to lists
-        self._warning_handler: Callable[[str, str], Match[str] | bool | None] 
| None = None  # noqa: E501
+        self._warning_handler: Callable[
+            [str, str], re.Match[str] | bool | None] | None = None
         self.write = self.action in WRITE_ACTIONS
         # Client side verification that the request is being performed
         # by a logged in user, and warn if it isn't a config username.
diff --git a/pywikibot/date.py b/pywikibot/date.py
index 886efeb..7fbe686 100644
--- a/pywikibot/date.py
+++ b/pywikibot/date.py
@@ -16,14 +16,7 @@
 from typing import TYPE_CHECKING

 from pywikibot import Site
-from pywikibot.backports import (
-    Any,
-    Callable,
-    Iterator,
-    Mapping,
-    Pattern,
-    Sequence,
-)
+from pywikibot.backports import Any, Callable, Iterator, Mapping, Sequence
 from pywikibot.site import BaseSite
 from pywikibot.tools import deprecate_arg, first_lower, first_upper
 from pywikibot.userinterfaces.transliteration import NON_ASCII_DIGITS
@@ -406,7 +399,7 @@

 def escapePattern2(
     pattern: str
-) -> tuple[Pattern[str], str, list[decoder_type]]:
+) -> tuple[re.Pattern[str], str, list[decoder_type]]:
     """Convert a string pattern into a regex expression and cache.

     Allows matching of any _digitDecoders inside the string. Returns a
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py
index 7e1a596..94051a9 100644
--- a/pywikibot/i18n.py
+++ b/pywikibot/i18n.py
@@ -39,7 +39,6 @@
     Iterable,
     Iterator,
     Mapping,
-    Match,
     Sequence,
 )
 from pywikibot.plural import plural_rule
@@ -459,7 +458,7 @@
         assert not callable(plural_rule)
         return plural_rule

-    def replace_plural(match: Match[str]) -> str:
+    def replace_plural(match: re.Match[str]) -> str:
         selector = match[1]
         variants = match[2]
         num = parameters[selector]
diff --git a/pywikibot/pagegenerators/_filters.py 
b/pywikibot/pagegenerators/_filters.py
index 641724d..ff81f47 100644
--- a/pywikibot/pagegenerators/_filters.py
+++ b/pywikibot/pagegenerators/_filters.py
@@ -13,7 +13,7 @@

 import pywikibot
 from pywikibot import config
-from pywikibot.backports import Generator, Iterable, Pattern, Sequence
+from pywikibot.backports import Generator, Iterable, Sequence
 from pywikibot.exceptions import NoPageError
 from pywikibot.proofreadpage import ProofreadPage
 from pywikibot.tools.itertools import filter_unique
@@ -28,9 +28,9 @@
                              list[pywikibot.page.BasePage]]
     PATTERN_STR_OR_SEQ_TYPE = Union[
         str,
-        Pattern[str],
+        re.Pattern[str],
         Sequence[str],
-        Sequence[Pattern[str]],
+        Sequence[re.Pattern[str]],
     ]


@@ -236,7 +236,7 @@
     """Regex filter."""

     @classmethod
-    def __filter_match(cls, regex: Sequence[Pattern[str]],
+    def __filter_match(cls, regex: Sequence[re.Pattern[str]],
                        string: str, quantifier: str) -> bool:
         """Return True if string matches precompiled regex list.

@@ -250,7 +250,7 @@

     @classmethod
     def __precompile(cls, regex: PATTERN_STR_OR_SEQ_TYPE,
-                     flag: int) -> list[Pattern[str]]:
+                     flag: int) -> list[re.Pattern[str]]:
         """Precompile the regex list if needed."""
         if isinstance(regex, list):
             regex_list = regex
diff --git a/pywikibot/site/_apisite.py b/pywikibot/site/_apisite.py
index 9c0f525..51bfe59 100644
--- a/pywikibot/site/_apisite.py
+++ b/pywikibot/site/_apisite.py
@@ -18,7 +18,7 @@

 import pywikibot
 from pywikibot import login
-from pywikibot.backports import DefaultDict, Iterable, Match
+from pywikibot.backports import DefaultDict, Iterable
 from pywikibot.backports import OrderedDict as OrderedDictType
 from pywikibot.comms import http
 from pywikibot.data import api
@@ -1298,7 +1298,7 @@
         def handle_warning(
             mod: str,
             warning: str
-        ) -> Match[str] | bool | None:
+        ) -> re.Match[str] | bool | None:
             return (mod == 'query' and re.match(
                 r'Unrecognized value for parameter [\'"]meta[\'"]: wikibase',
                 warning))
diff --git a/pywikibot/site/_basesite.py b/pywikibot/site/_basesite.py
index abd051b..0100cef 100644
--- a/pywikibot/site/_basesite.py
+++ b/pywikibot/site/_basesite.py
@@ -1,6 +1,6 @@
 """Objects with site methods independent of the communication interface."""
 #
-# (C) Pywikibot team, 2008-2024
+# (C) Pywikibot team, 2008-2025
 #
 # Distributed under the terms of the MIT license.
 #
@@ -13,7 +13,6 @@
 from warnings import warn

 import pywikibot
-from pywikibot.backports import Pattern
 from pywikibot.exceptions import (
     Error,
     FamilyMaintenanceWarning,
@@ -380,7 +379,7 @@
         return linkfam != self.family.name or linkcode != self.code

     @property
-    def redirect_regex(self) -> Pattern[str]:
+    def redirect_regex(self) -> re.Pattern[str]:
         """Return a compiled regular expression matching on redirect pages.

         Group 1 in the regex match object will be the target title.
diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py
index 97ea55a..19d074d 100644
--- a/pywikibot/textlib.py
+++ b/pywikibot/textlib.py
@@ -17,9 +17,8 @@
 from typing import NamedTuple

 import pywikibot
-from pywikibot.backports import Callable, Container, Iterable, Match
+from pywikibot.backports import Callable, Container, Iterable
 from pywikibot.backports import OrderedDict as OrderedDictType
-from pywikibot.backports import Pattern
 from pywikibot.backports import Sequence as SequenceType
 from pywikibot.backports import pairwise
 from pywikibot.exceptions import InvalidTitleError, SiteDefinitionError
@@ -42,7 +41,7 @@


 # cache for replaceExcept to avoid recompile or regexes each call
-_regex_cache: dict[str, Pattern[str]] = {}
+_regex_cache: dict[str, re.Pattern[str]] = {}

 # The regex below collects nested templates, providing simpler
 # identification of templates used at the top-level of wikitext.
@@ -320,7 +319,7 @@
 def get_regexes(
     keys: str | Iterable[str],
     site: pywikibot.site.BaseSite | None = None
-) -> list[Pattern[str]]:
+) -> list[re.Pattern[str]]:
     """Fetch compiled regexes.

     .. versionchanged:: 8.2
@@ -382,9 +381,9 @@


 def replaceExcept(text: str,
-                  old: str | Pattern[str],
-                  new: str | Callable[[Match[str]], str],
-                  exceptions: SequenceType[str | Pattern[str]],
+                  old: str | re.Pattern[str],
+                  new: str | Callable[[re.Match[str]], str],
+                  exceptions: SequenceType[str | re.Pattern[str]],
                   caseInsensitive: bool = False,
                   allowoverlap: bool = False,
                   marker: str = '',
@@ -2203,11 +2202,11 @@
     .. versionadded:: 8.0
     """

-    time: Pattern[str]
-    tzinfo: Pattern[str]
-    year: Pattern[str]
-    month: Pattern[str]
-    day: Pattern[str]
+    time: re.Pattern[str]
+    tzinfo: re.Pattern[str]
+    year: re.Pattern[str]
+    month: re.Pattern[str]
+    day: re.Pattern[str]


 class TimeStripper:
@@ -2352,7 +2351,7 @@

     def _last_match_and_replace(self,
                                 txt: str,
-                                pat) -> tuple[str, Match[str] | None]:
+                                pat) -> tuple[str, re.Match[str] | None]:
         """Take the rightmost match and replace with marker.

         It does so to prevent spurious earlier matches.
@@ -2365,7 +2364,7 @@

         m = all_matches[-1]

-        def marker(m: Match[str]):
+        def marker(m: re.Match[str]):
             """Replace exactly the same number of matched characters.

             Same number of chars shall be replaced, in order to be able
diff --git a/scripts/archivebot.py b/scripts/archivebot.py
index d0538ed..e1c90d1 100755
--- a/scripts/archivebot.py
+++ b/scripts/archivebot.py
@@ -208,7 +208,7 @@

 import pywikibot
 from pywikibot import i18n
-from pywikibot.backports import Pattern, pairwise
+from pywikibot.backports import pairwise
 from pywikibot.exceptions import Error, NoPageError
 from pywikibot.textlib import (
     TimeStripper,
@@ -298,7 +298,7 @@
     return val, unit


-def template_title_regex(tpl_page: pywikibot.Page) -> Pattern:
+def template_title_regex(tpl_page: pywikibot.Page) -> re.Pattern:
     """Return a regex that matches to variations of the template title.

     It supports the transcluding variant as well as localized namespaces
diff --git a/scripts/replace.py b/scripts/replace.py
index 176da68..d87345a 100755
--- a/scripts/replace.py
+++ b/scripts/replace.py
@@ -175,7 +175,7 @@

 import pywikibot
 from pywikibot import editor, fixes, i18n, pagegenerators, textlib
-from pywikibot.backports import Generator, Pattern, batched
+from pywikibot.backports import Generator, batched
 from pywikibot.bot import ExistingPageBot, SingleSiteBot
 from pywikibot.exceptions import InvalidPageError, NoPageError
 from pywikibot.tools import chars
@@ -879,8 +879,8 @@


 def handle_sql(sql: str,
-               replacements: list[Pattern],
-               exceptions: list[Pattern]) -> Generator:
+               replacements: list[re.Pattern],
+               exceptions: list[re.Pattern]) -> Generator:
     """Handle default sql query.

     .. versionadded:: 7.0

--
To view, visit 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1200451?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: I70eaa7d5394fe00789ca3023e2176e237d633183
Gerrit-Change-Number: 1200451
Gerrit-PatchSet: 4
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