jenkins-bot has submitted this change. (
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1184713?usp=email )
Change subject: fix some typing errors raised by mypy
......................................................................
fix some typing errors raised by mypy
Also rename module parameter of ParamInfo.parameter() method to
module_name, deprecate the old name and fix its call in
change_pagelang.py script.
Also update mypy settings for fixed issues.
Change-Id: I1f30de93e8cc7b99f07d46dc4d7fbb06a158f67d
---
M .pre-commit-config.yaml
M conftest.py
M make_dist.py
M pywikibot/comms/http.py
M pywikibot/config.py
M pywikibot/cosmetic_changes.py
M pywikibot/data/api/_paraminfo.py
M pywikibot/data/mysql.py
M pywikibot/logging.py
M pywikibot/pagegenerators/__init__.py
M pywikibot/site/_datasite.py
M pywikibot/site/_generators.py
M pywikibot/userinterfaces/terminal_interface_base.py
M scripts/change_pagelang.py
14 files changed, 44 insertions(+), 34 deletions(-)
Approvals:
jenkins-bot: Verified
Xqt: Looks good to me, approved
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 090c22d..3ceb417 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -122,10 +122,11 @@
# Test for files which already passed in past.
# They should be also used in conftest.py to exclude them from
non-voting mypy test.
files: >
- ^pywikibot/(__metadata__|config|echo|exceptions|fixes|time)\.py$|
+
^pywikibot/(__metadata__|config|echo|exceptions|fixes|logging|time)\.py$|
^pywikibot/(comms|data|families|specialbots)/__init__\.py$|
^pywikibot/families/[a-z][a-z\d]+_family\.py$|
^pywikibot/page/(__init__|_decorators|_revision)\.py$|
+ ^pywikibot/pagegenerators/__init__\.py$|
^pywikibot/scripts/(?:i18n/)?__init__\.py$|
^pywikibot/site/(__init__|_basesite|_decorators|_extensions|_interwikimap|_tokenwallet|_upload)\.py$|
^pywikibot/tools/(_logging|_unidata|formatter)\.py$|
diff --git a/conftest.py b/conftest.py
index 27f2480..c49444b 100644
--- a/conftest.py
+++ b/conftest.py
@@ -16,10 +16,11 @@
EXCLUDE_PATTERN = re.compile(
r'(?:'
- r'(__metadata__|config|echo|exceptions|fixes|time)|'
+ r'(__metadata__|config|echo|exceptions|fixes|logging|time)|'
r'(comms|data|families|specialbots)/__init__|'
r'families/[a-z][a-z\d]+_family|'
r'page/(__init__|_decorators|_revision)|'
+ r'pagegenerators/__init__|'
r'scripts/(i18n/)?__init__|'
r'site/(__init__|_basesite|_decorators|_extensions|_interwikimap|'
r'_tokenwallet|_upload)|'
diff --git a/make_dist.py b/make_dist.py
index c2a519e..238928a 100755
--- a/make_dist.py
+++ b/make_dist.py
@@ -247,7 +247,7 @@
info('<<lightyellow>>done')
-def handle_args() -> tuple[bool, bool, bool, bool]:
+def handle_args() -> tuple[bool, bool, bool, bool, bool]:
"""Handle arguments and print documentation if requested.
:return: Return whether dist is to be installed locally or to be
diff --git a/pywikibot/comms/http.py b/pywikibot/comms/http.py
index f6d4bc0..281cf16 100644
--- a/pywikibot/comms/http.py
+++ b/pywikibot/comms/http.py
@@ -196,7 +196,7 @@
def user_agent(site: pywikibot.site.BaseSite | None = None,
- format_string: str = '') -> str:
+ format_string: str | None = '') -> str:
"""Generate the user agent string for a given site and format.
:param site: The site for which this user agent is intended. May be
@@ -211,7 +211,7 @@
pywikibot.bot.calledModuleName()))
values.update(dict.fromkeys(['family', 'code', 'lang', 'site'], ''))
- script_comments = []
+ script_comments: list[str] = []
if config.user_agent_description:
script_comments.append(config.user_agent_description)
@@ -539,7 +539,7 @@
pywikibot.warning(
f'Unknown or invalid encoding {encoding!r} for {response.url}')
except UnicodeDecodeError as e:
- pywikibot.warning(f'{e} found in {content}')
+ pywikibot.warning(f'{e} found in {content!r}')
else:
return encoding
diff --git a/pywikibot/config.py b/pywikibot/config.py
index e322f35..ced631c 100644
--- a/pywikibot/config.py
+++ b/pywikibot/config.py
@@ -146,7 +146,7 @@
# User agent description
# This is a free-form string that can be user to describe specific bot/tool,
# provide contact information, etc.
-user_agent_description = None
+user_agent_description: str | None = None
# Fake user agent.
# Some external websites reject bot-like user agents. It is possible to use
# fake user agents in requests to these websites.
@@ -225,7 +225,7 @@
# use them. In this case, the password file should contain a BotPassword object
# in the following format:
# (username, BotPassword(botname, botpassword))
-password_file = None
+password_file: str | os.PathLike | None = None
# edit summary to use if not supplied by bot script
# WARNING: this should NEVER be used in practice, ALWAYS supply a more
@@ -498,7 +498,7 @@
# transliteration_target = console_encoding
# After emitting the warning, this last option will be set.
-transliteration_target = None
+transliteration_target: str | None = None
# The encoding in which textfiles are stored, which contain lists of page
# titles. The most used is 'utf-8'; 'utf-8-sig' recognizes BOM.
diff --git a/pywikibot/cosmetic_changes.py b/pywikibot/cosmetic_changes.py
index f97c7a7..af94592 100644
--- a/pywikibot/cosmetic_changes.py
+++ b/pywikibot/cosmetic_changes.py
@@ -735,7 +735,7 @@
return text
# iterate stripped sections and create a new page body
- new_body: textlib.SectionList[textlib.Section] = []
+ new_body: textlib.SectionList = textlib.SectionList()
for i, strip_section in enumerate(strip_sections):
current_dep = sections[i].level
try:
diff --git a/pywikibot/data/api/_paraminfo.py b/pywikibot/data/api/_paraminfo.py
index e9bf0af..44fd7c4 100644
--- a/pywikibot/data/api/_paraminfo.py
+++ b/pywikibot/data/api/_paraminfo.py
@@ -12,7 +12,12 @@
import pywikibot
from pywikibot import config
from pywikibot.backports import Iterable, batched
-from pywikibot.tools import classproperty, deprecated, remove_last_args
+from pywikibot.tools import (
+ classproperty,
+ deprecated,
+ deprecated_args,
+ remove_last_args,
+)
__all__ = ['ParamInfo']
@@ -48,11 +53,11 @@
self._paraminfo: dict[str, Any] = {}
# Cached data.
- self._prefix_map = {}
+ self._prefix_map: dict[str, str] = {}
self._action_modules = frozenset() # top level modules
self._modules = {} # filled in _init() (and enlarged in fetch)
- self._limit = None
+ self._limit: int | None = None
self._preloaded_modules = self.init_modules
if preloaded_modules:
@@ -331,9 +336,10 @@
"""Return number of cached modules."""
return len(self._paraminfo)
+ @deprecated_args(module='module_name') # since 10.5.0
def parameter(
self,
- module: str,
+ module_name: str,
param_name: str
) -> dict[str, Any] | None:
"""Get details about one modules parameter.
@@ -345,9 +351,9 @@
:return: metadata that describes how the parameter may be used
"""
try:
- module = self[module]
+ module = self[module_name]
except KeyError:
- raise ValueError(f"paraminfo for '{module}' not loaded")
+ raise ValueError(f"paraminfo for '{module_name}' not loaded")
try:
params = module['parameters']
diff --git a/pywikibot/data/mysql.py b/pywikibot/data/mysql.py
index 6193a4d..a171b30 100644
--- a/pywikibot/data/mysql.py
+++ b/pywikibot/data/mysql.py
@@ -1,6 +1,6 @@
"""Miscellaneous helper functions for mysql queries."""
#
-# (C) Pywikibot team, 2016-2022
+# (C) Pywikibot team, 2016-2025
#
# Distributed under the terms of the MIT license.
#
@@ -44,7 +44,7 @@
"""
# These are specified in config.py or your user config file
if verbose is None:
- verbose = config.verbose_output
+ verbose = config.verbose_output > 0
if config.db_connect_file is None:
credentials = {'user': config.db_username,
diff --git a/pywikibot/logging.py b/pywikibot/logging.py
index 4df2669..c86ac7e 100644
--- a/pywikibot/logging.py
+++ b/pywikibot/logging.py
@@ -24,7 +24,7 @@
- :python:`Logging Cookbook<howto/logging-cookbook.html>`
"""
#
-# (C) Pywikibot team, 2010-2024
+# (C) Pywikibot team, 2010-2025
#
# Distributed under the terms of the MIT license.
#
@@ -61,7 +61,7 @@
"""
_init_routines: list[Callable[[], Any]] = []
-_inited_routines = set()
+_inited_routines: set[Callable[[], Any]] = set()
def add_init_routine(routine: Callable[[], Any]) -> None:
@@ -349,7 +349,7 @@
if msg is None:
exc_type, value, _tb = sys.exc_info()
msg = str(value)
- if not exc_info:
+ if exc_type is not None and not exc_info:
msg += f' ({exc_type.__name__})'
assert msg is not None
error(msg, *args, exc_info=exc_info, **kwargs)
diff --git a/pywikibot/pagegenerators/__init__.py
b/pywikibot/pagegenerators/__init__.py
index dea213c..58cfb4b 100644
--- a/pywikibot/pagegenerators/__init__.py
+++ b/pywikibot/pagegenerators/__init__.py
@@ -12,7 +12,7 @@
¶ms;
"""
#
-# (C) Pywikibot team, 2008-2024
+# (C) Pywikibot team, 2008-2025
#
# Distributed under the terms of the MIT license.
#
@@ -594,7 +594,9 @@
if not return_talk_only or page.isTalkPage():
yield page
if not page.isTalkPage():
- yield page.toggleTalkPage()
+ talk_page = page.toggleTalkPage()
+ if talk_page is not None:
+ yield talk_page
def RepeatingGenerator(
diff --git a/pywikibot/site/_datasite.py b/pywikibot/site/_datasite.py
index d67f2ba..cf09ee3 100644
--- a/pywikibot/site/_datasite.py
+++ b/pywikibot/site/_datasite.py
@@ -212,7 +212,7 @@
if not hasattr(self, '_entity_namespaces'):
self._cache_entity_namespaces()
for batch in batched(pagelist, groupsize):
- req = {'ids': [], 'titles': [], 'sites': []}
+ req: dict[str, list[str]] = {'ids': [], 'titles': [], 'sites': []}
for p in batch:
if isinstance(p, pywikibot.page.WikibaseEntity):
ident = p._defined_by()
diff --git a/pywikibot/site/_generators.py b/pywikibot/site/_generators.py
index 2d4a7d1..9ba50f0 100644
--- a/pywikibot/site/_generators.py
+++ b/pywikibot/site/_generators.py
@@ -89,7 +89,7 @@
# Store the order of the input data.
priority_dict = dict(zip(batch, range(len(batch))))
- prio_queue = []
+ prio_queue: list[tuple[int, pywikibot.Page]] = []
next_prio = 0
params = {'pageids': batch}
rvgen = api.PropertyGenerator('info', site=self, parameters=params)
@@ -172,7 +172,7 @@
# Do not use p.pageid property as it will force page loading.
pageids = [str(p._pageid) for p in batch
if hasattr(p, '_pageid') and p._pageid > 0]
- cache = {}
+ cache: dict[str, tuple[int, pywikibot.Page]] = {}
# In case of duplicates, return the first entry.
for priority, page in enumerate(batch):
try:
@@ -181,7 +181,7 @@
except InvalidTitleError:
pywikibot.exception()
- prio_queue = []
+ prio_queue: list[tuple[int, pywikibot.Page]] = []
next_prio = 0
rvgen = api.PropertyGenerator(props, site=self)
rvgen.set_maximum_items(-1) # suppress use of "rvlimit" parameter
diff --git a/pywikibot/userinterfaces/terminal_interface_base.py
b/pywikibot/userinterfaces/terminal_interface_base.py
index f2a07c6..6c4c8e3 100644
--- a/pywikibot/userinterfaces/terminal_interface_base.py
+++ b/pywikibot/userinterfaces/terminal_interface_base.py
@@ -11,7 +11,7 @@
import re
import sys
import threading
-from typing import Any, NoReturn
+from typing import Any, Literal, NoReturn, TextIO
import pywikibot
from pywikibot import config
@@ -95,7 +95,7 @@
def init_handlers(
self,
root_logger,
- default_stream: str = 'stderr'
+ default_stream: TextIO | Literal['stderr', 'stdout'] = 'stderr'
) -> None:
"""Initialize the handlers for user output.
@@ -536,15 +536,15 @@
choice = self.input(question, default=default, force=force)
try:
- choice = int(choice) - 1
+ parsedchoice = int(choice) - 1
except (TypeError, ValueError):
if choice in answers:
return choice
- choice = -1
+ parsedchoice = -1
# User typed choice number
- if 0 <= choice < len(answers):
- return answers[choice]
+ if 0 <= parsedchoice < len(answers):
+ return answers[parsedchoice]
if force:
raise ValueError(
diff --git a/scripts/change_pagelang.py b/scripts/change_pagelang.py
index f6f327b..bedd622 100755
--- a/scripts/change_pagelang.py
+++ b/scripts/change_pagelang.py
@@ -154,7 +154,7 @@
site = pywikibot.Site()
specialpages = site.siteinfo['specialpagealiases']
specialpagelist = {item['realname'] for item in specialpages}
- allowedlanguages = site._paraminfo.parameter(module='setpagelanguage',
+ allowedlanguages = site._paraminfo.parameter(module_name='setpagelanguage',
param_name='lang')['type']
# Check if the special page PageLanguage is enabled on the wiki
# If it is not, page languages can't be set, and there's no point in
--
To view, visit
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1184713?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: I1f30de93e8cc7b99f07d46dc4d7fbb06a158f67d
Gerrit-Change-Number: 1184713
Gerrit-PatchSet: 4
Gerrit-Owner: DerIch27 <[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]