jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/767276 )
Change subject: add return type annotations to some magaic methods ......................................................................
add return type annotations to some magaic methods
Change-Id: Ia723f34b1ae3bf3e2580a53b6885bf5ff303e587 --- M pywikibot/__init__.py M pywikibot/comms/eventstreams.py M pywikibot/data/api.py M pywikibot/data/sparql.py M pywikibot/family.py M pywikibot/page/__init__.py M pywikibot/page/_collections.py M pywikibot/page/_revision.py M pywikibot/site/_basesite.py M pywikibot/site/_namespace.py M pywikibot/site/_tokenwallet.py M pywikibot/site_detect.py M pywikibot/specialbots/_upload.py M pywikibot/textlib.py M pywikibot/tools/__init__.py M scripts/interwiki.py M scripts/replace.py M scripts/speedy_delete.py M scripts/unusedfiles.py 19 files changed, 80 insertions(+), 68 deletions(-)
Approvals: JJMC89: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py index c6d21a4..29d266e 100644 --- a/pywikibot/__init__.py +++ b/pywikibot/__init__.py @@ -801,7 +801,7 @@
_items = ('text', 'language')
- def __init__(self, text: str, language: str): + def __init__(self, text: str, language: str) -> None: """ Create a new WbMonolingualText object.
diff --git a/pywikibot/comms/eventstreams.py b/pywikibot/comms/eventstreams.py index 6db0a5c..78c0fef 100644 --- a/pywikibot/comms/eventstreams.py +++ b/pywikibot/comms/eventstreams.py @@ -74,7 +74,7 @@ >>> del stream """
- def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: """Initializer.
:keyword site: a project site object. Used when no url is given @@ -124,7 +124,7 @@ kwargs.setdefault('timeout', config.socket_timeout) self.sse_kwargs = kwargs
- def __repr__(self): + def __repr__(self) -> str: """Return representation string.""" kwargs = self.sse_kwargs.copy() if self._site != Site(): diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py index ab2441d..51db7e0 100644 --- a/pywikibot/data/api.py +++ b/pywikibot/data/api.py @@ -835,7 +835,7 @@ """Remove the item by setting it to None.""" self[name] = None
- def __contains__(self, name): + def __contains__(self, name) -> bool: """Return True if option has been set.""" return name in self._enabled or name in self._disabled
@@ -850,7 +850,7 @@ for disabled in self._disabled: yield '!{}'.format(disabled)
- def __len__(self): + def __len__(self) -> int: """Return the number of enabled and disabled options.""" return len(self._enabled) + len(self._disabled)
@@ -921,7 +921,7 @@ max_retries: Optional[int] = None, retry_wait: Optional[int] = None, use_get: Optional[bool] = None, - parameters=_PARAM_DEFAULT, **kwargs): + parameters=_PARAM_DEFAULT, **kwargs) -> None: """ Create a new Request instance with the given parameters.
@@ -1186,7 +1186,7 @@ """Implement dict interface.""" return list(self._params.keys())
- def __contains__(self, key): + def __contains__(self, key) -> bool: """Implement dict interface.""" return key in self._params
@@ -1194,7 +1194,7 @@ """Implement dict interface.""" return iter(self._params)
- def __len__(self): + def __len__(self) -> int: """Implement dict interface.""" return len(self._params)
@@ -1318,13 +1318,13 @@ """ return encode_url(self._encoded_items())
- def __str__(self): + def __str__(self) -> str: """Return a string representation.""" return unquote(self.site.scriptpath() + '/api.php?' + self._http_param_string())
- def __repr__(self): + def __repr__(self) -> str: """Return internal representation.""" return '{}.{}<{}->{!r}>'.format(self.__class__.__module__, self.__class__.__name__, @@ -2203,7 +2203,7 @@ # set_namespace call. Only to be used by _check_result_namespace. _namespaces = None
- def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: """ Initialize a QueryGenerator object.
diff --git a/pywikibot/data/sparql.py b/pywikibot/data/sparql.py index b1c7c15..7277461 100644 --- a/pywikibot/data/sparql.py +++ b/pywikibot/data/sparql.py @@ -31,7 +31,7 @@ endpoint: Optional[str] = None, entity_url: Optional[str] = None, repo=None, max_retries: Optional[int] = None, - retry_wait: Optional[float] = None): + retry_wait: Optional[float] = None) -> None: """ Create endpoint.
@@ -208,7 +208,7 @@ """Create a SparqlNode.""" self.value = value
- def __str__(self): + def __str__(self) -> str: return self.value
@@ -231,7 +231,7 @@ return self.value[urllen:] return None
- def __repr__(self): + def __repr__(self) -> str: return '<' + self.value + '>'
@@ -244,7 +244,7 @@ self.type = data.get('datatype') self.language = data.get('xml:lang')
- def __repr__(self): + def __repr__(self) -> str: if self.type: return self.value + '^^' + self.type if self.language: @@ -259,7 +259,7 @@ """Create Bnode.""" super().__init__(data.get('value'))
- def __repr__(self): + def __repr__(self) -> str: return '_:' + self.value
diff --git a/pywikibot/family.py b/pywikibot/family.py index 879be6d..1221fa8 100644 --- a/pywikibot/family.py +++ b/pywikibot/family.py @@ -920,10 +920,10 @@ def __hash__(self): return hash(self.name)
- def __str__(self): + def __str__(self) -> str: return self.name
- def __repr__(self): + def __repr__(self) -> str: return 'Family("{}")'.format(self.name)
def shared_image_repository(self, code): diff --git a/pywikibot/page/__init__.py b/pywikibot/page/__init__.py index 4c9eb7d..8fcbb94 100644 --- a/pywikibot/page/__init__.py +++ b/pywikibot/page/__init__.py @@ -135,7 +135,7 @@ '_pageimage', '_item', '_lintinfo', )
- def __init__(self, source, title='', ns=0): + def __init__(self, source, title='', ns=0) -> None: """ Instantiate a Page object.
@@ -2080,7 +2080,7 @@
"""Page: A MediaWiki page."""
- def __init__(self, source, title: str = '', ns=0): + def __init__(self, source, title: str = '', ns=0) -> None: """Instantiate a Page object.""" if isinstance(source, pywikibot.site.BaseSite): if not title: @@ -2280,7 +2280,7 @@ Supports the same interface as Page, with some added methods. """
- def __init__(self, source, title: str = ''): + def __init__(self, source, title: str = '') -> None: """Initializer.""" self._file_revisions = {} # dictionary to cache File history. super().__init__(source, title, 6) @@ -2545,7 +2545,7 @@
"""A page in the Category: namespace."""
- def __init__(self, source, title: str = '', sort_key=None): + def __init__(self, source, title: str = '', sort_key=None) -> None: """ Initializer.
@@ -2841,7 +2841,7 @@ This class also represents the Wiki page User:<username> """
- def __init__(self, source, title=''): + def __init__(self, source, title='') -> None: """ Initializer for a User object.
@@ -3262,7 +3262,7 @@
DATA_ATTRIBUTES = {} # type: Dict[str, Any]
- def __init__(self, repo, id_=None): + def __init__(self, repo, id_=None) -> None: """ Initializer.
@@ -3278,7 +3278,7 @@ "'{}' is not a valid {} page title" .format(self.id, self.entity_type))
- def __repr__(self): + def __repr__(self) -> str: if self.id != '-1': return 'pywikibot.page.{}({!r}, {!r})'.format( self.__class__.__name__, self.repo, self.id) @@ -3574,7 +3574,7 @@
_cache_attrs = BasePage._cache_attrs + ('_content', )
- def __init__(self, site, title='', **kwargs): + def __init__(self, site, title='', **kwargs) -> None: """ Initializer.
@@ -3900,7 +3900,7 @@ 'sitelinks': SiteLinkCollection, }
- def __init__(self, site, title=None, ns=None): + def __init__(self, site, title=None, ns=None) -> None: """ Initializer.
@@ -4365,7 +4365,7 @@ 'claims': ClaimCollection, }
- def __init__(self, source, title=None, datatype=None): + def __init__(self, source, title=None, datatype=None) -> None: """ Initializer.
@@ -4471,7 +4471,7 @@ SNAK_TYPES = ('value', 'somevalue', 'novalue')
def __init__(self, site, pid, snak=None, hash=None, is_reference=False, - is_qualifier=False, rank='normal', **kwargs): + is_qualifier=False, rank='normal', **kwargs) -> None: """ Initializer.
@@ -4516,7 +4516,7 @@ for source in values: source.on_item = item
- def __repr__(self): + def __repr__(self) -> str: """Return the representation string.""" return '{cls_name}.fromJSON({}, {})'.format( repr(self.repo), self.toJSON(), cls_name=type(self).__name__) @@ -5033,7 +5033,7 @@ """Give access to class values by key.""" return getattr(self, key)
- def __repr__(self): + def __repr__(self) -> str: """Return a more complete string representation.""" return repr(self.__dict__)
@@ -5087,7 +5087,7 @@ else: self._sitekey = site
- def __repr__(self): + def __repr__(self) -> str: """Return a more complete string representation.""" assert isinstance(self._items, tuple) assert all(isinstance(item, (bytes, str)) for item in self._items) @@ -5270,7 +5270,7 @@ '|&#x[0-9A-Fa-f]+;' )
- def __init__(self, text, source=None, default_namespace=0): + def __init__(self, text, source=None, default_namespace=0) -> None: """ Initializer.
diff --git a/pywikibot/page/_collections.py b/pywikibot/page/_collections.py index f4fe56b..5e0b984 100644 --- a/pywikibot/page/_collections.py +++ b/pywikibot/page/_collections.py @@ -55,14 +55,14 @@ def __iter__(self): return iter(self._data)
- def __len__(self): + def __len__(self) -> int: return len(self._data)
- def __contains__(self, key): + def __contains__(self, key) -> bool: key = self.normalizeKey(key) return key in self._data
- def __repr__(self): + def __repr__(self) -> str: return '{}({})'.format(type(self), self._data)
@staticmethod @@ -222,13 +222,13 @@ def __iter__(self): return iter(self._data)
- def __len__(self): + def __len__(self) -> int: return len(self._data)
- def __contains__(self, key): + def __contains__(self, key) -> bool: return key in self._data
- def __repr__(self): + def __repr__(self) -> str: return '{}({})'.format(type(self), self._data)
@classmethod @@ -384,10 +384,10 @@ def __iter__(self): return iter(self._data)
- def __len__(self): + def __len__(self) -> int: return len(self._data)
- def __contains__(self, key): + def __contains__(self, key) -> bool: key = self.getdbName(key) return key in self._data
diff --git a/pywikibot/page/_revision.py b/pywikibot/page/_revision.py index 6594baf..2aef3c5 100644 --- a/pywikibot/page/_revision.py +++ b/pywikibot/page/_revision.py @@ -79,11 +79,11 @@ """Provide Revision data as iterator.""" return iter(self._data)
- def __repr__(self): + def __repr__(self) -> str: """String representation of Revision.""" return '{}({})'.format(self.__class__.__name__, self._data)
- def __str__(self): + def __str__(self) -> str: """Printable representation of Revision data.""" return str(self._data)
diff --git a/pywikibot/site/_basesite.py b/pywikibot/site/_basesite.py index ad5a8d7..c2a02f9 100644 --- a/pywikibot/site/_basesite.py +++ b/pywikibot/site/_basesite.py @@ -203,7 +203,7 @@ raise AttributeError("{} instance has no attribute '{}'" .format(self.__class__.__name__, attr))
- def __str__(self): + def __str__(self) -> str: """Return string representing this Site's name and code.""" return self.family.name + ':' + self.code
@@ -212,7 +212,7 @@ """String representing this Site's name and code.""" return SelfCallString(self.__str__())
- def __repr__(self): + def __repr__(self) -> str: """Return internal representation.""" return '{}("{}", "{}")'.format( self.__class__.__name__, self.code, self.family) diff --git a/pywikibot/site/_namespace.py b/pywikibot/site/_namespace.py index 027a836..120b06b 100644 --- a/pywikibot/site/_namespace.py +++ b/pywikibot/site/_namespace.py @@ -159,7 +159,7 @@ """ return True
- def __len__(self): + def __len__(self) -> int: """Obtain length of the iterable.""" return len(self._distinct())
@@ -187,7 +187,7 @@
return name + ':'
- def __str__(self): + def __str__(self) -> str: """Return the canonical string representation.""" return self.canonical_prefix()
@@ -199,11 +199,11 @@ """Return the custom name with required colons.""" return Namespace._colons(self.id, self.custom_name)
- def __int__(self): + def __int__(self) -> int: """Return the namespace id.""" return self.id
- def __index__(self): + def __index__(self) -> int: """Return the namespace id.""" return self.id
@@ -244,7 +244,7 @@ """Return the ID as a comparison key.""" return self.id
- def __repr__(self): + def __repr__(self) -> str: """Return a reconstructable representation.""" standard_attr = ['id', 'custom_name', 'canonical_name', 'aliases'] extra = [(key, self.__dict__[key]) @@ -372,7 +372,7 @@
return self.__getattribute__(attr)
- def __len__(self): + def __len__(self) -> int: """Get the number of namespaces.""" return len(self._namespaces)
diff --git a/pywikibot/site/_tokenwallet.py b/pywikibot/site/_tokenwallet.py index 564ec77..fd49f32 100644 --- a/pywikibot/site/_tokenwallet.py +++ b/pywikibot/site/_tokenwallet.py @@ -87,14 +87,14 @@ "Action '{}' is not allowed for user {} on {} wiki." .format(key, self.site.user(), self.site))
- def __contains__(self, key): + def __contains__(self, key) -> bool: """Return True if the given token name is cached.""" return key in self._tokens.setdefault(self.site.user(), {})
- def __str__(self): + def __str__(self) -> str: """Return a str representation of the internal tokens dictionary.""" return self._tokens.__str__()
- def __repr__(self): + def __repr__(self) -> str: """Return a representation of the internal tokens dictionary.""" return self._tokens.__repr__() diff --git a/pywikibot/site_detect.py b/pywikibot/site_detect.py index 63e2fad..5476890 100644 --- a/pywikibot/site_detect.py +++ b/pywikibot/site_detect.py @@ -30,7 +30,7 @@
"""Minimal wiki site class."""
- def __init__(self, fromurl, **kwargs): + def __init__(self, fromurl, **kwargs) -> None: """ Initializer.
@@ -90,7 +90,7 @@ raise RuntimeError('Unable to determine articlepath: ' '{}'.format(self.fromurl))
- def __repr__(self): + def __repr__(self) -> str: return '{}("{}")'.format( self.__class__.__name__, self.fromurl)
diff --git a/pywikibot/specialbots/_upload.py b/pywikibot/specialbots/_upload.py index bf6350a..bb2cd34 100644 --- a/pywikibot/specialbots/_upload.py +++ b/pywikibot/specialbots/_upload.py @@ -44,7 +44,7 @@ summary: Optional[str] = None, filename_prefix: Optional[str] = None, force_if_shared: bool = False, - **kwargs): + **kwargs) -> None: """Initializer.
.. versionchanged:: 6.2 diff --git a/pywikibot/textlib.py b/pywikibot/textlib.py index cea6c70..1821fb2 100644 --- a/pywikibot/textlib.py +++ b/pywikibot/textlib.py @@ -1842,7 +1842,7 @@ """Return no daylight savings time.""" return datetime.timedelta(0)
- def __repr__(self): + def __repr__(self) -> str: """Return the internal representation of the timezone.""" return '{}({}, {})'.format( self.__class__.__name__, diff --git a/pywikibot/tools/__init__.py b/pywikibot/tools/__init__.py index 6e52f2c..c6e476b 100644 --- a/pywikibot/tools/__init__.py +++ b/pywikibot/tools/__init__.py @@ -22,7 +22,8 @@ from functools import total_ordering, wraps from importlib import import_module from itertools import chain, zip_longest -from typing import Any, Optional +from types import TracebackType +from typing import Any, Optional, Type from warnings import catch_warnings, showwarning, warn
import pkg_resources @@ -176,7 +177,12 @@ """Catch all warnings and store them in `self.log`.""" self.log = super().__enter__()
- def __exit__(self, exc_type, exc_val, exc_tb) -> None: + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType] + ) -> None: """Stop logging warnings and show those that do not match to params.""" super().__exit__(exc_type, exc_val, exc_tb) for warning in self.log: @@ -562,7 +568,7 @@ """Delegate attributes and methods to self._lock.""" return getattr(self._lock, name)
- def __repr__(self): + def __repr__(self) -> str: """Representation of tools.RLock instance.""" return repr(self._lock).replace( '_thread.RLock', @@ -609,7 +615,7 @@ """
def __init__(self, group=None, target=None, name='GeneratorThread', - args=(), kwargs=None, qsize=65536): + args=(), kwargs=None, qsize=65536) -> None: """Initializer. Takes same keyword arguments as threading.Thread.
target must be a generator function (or other callable that returns @@ -748,7 +754,7 @@
_logger = 'threadlist'
- def __init__(self, limit=128, wait_time=2, *args): + def __init__(self, limit=128, wait_time=2, *args) -> None: """Initializer.
:param limit: the number of simultaneous threads @@ -1095,7 +1101,7 @@ return self.popleft() raise StopIteration
- def __repr__(self): + def __repr__(self) -> str: """Provide an object representation without clearing the content.""" items = list(self) result = '{}({})'.format(self.__class__.__name__, items) diff --git a/scripts/interwiki.py b/scripts/interwiki.py index fff4d5c..6e9d5a5 100755 --- a/scripts/interwiki.py +++ b/scripts/interwiki.py @@ -2081,7 +2081,7 @@ while not self.isDone(): self.queryStep()
- def __len__(self): + def __len__(self) -> int: """Return length of subjects.""" return len(self.subjects)
diff --git a/scripts/replace.py b/scripts/replace.py index 035ba41..00c9419 100755 --- a/scripts/replace.py +++ b/scripts/replace.py @@ -536,7 +536,13 @@ about the missing site """
- def __init__(self, generator, replacements, exceptions=None, **kwargs): + def __init__( + self, + generator, + replacements, + exceptions=None, + **kwargs + ) -> None: """Initializer.""" self.available_options.update({ 'addcat': None, diff --git a/scripts/speedy_delete.py b/scripts/speedy_delete.py index dcbcde1..5aff328 100755 --- a/scripts/speedy_delete.py +++ b/scripts/speedy_delete.py @@ -314,7 +314,7 @@ }, }
- def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: """Initializer.
:keyword site: the site to work on diff --git a/scripts/unusedfiles.py b/scripts/unusedfiles.py index c891f05..c61bee5 100755 --- a/scripts/unusedfiles.py +++ b/scripts/unusedfiles.py @@ -80,7 +80,7 @@ 'usertemplate': '', }
- def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: """Initializer.""" super().__init__(**kwargs)
pywikibot-commits@lists.wikimedia.org