pre-commit Updates (#3221)

This commit is contained in:
pre-commit-ci[bot] 2022-09-17 15:08:54 +02:00 committed by GitHub
parent 436b5ff7a8
commit 5480be4c25
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 31 additions and 35 deletions

View file

@ -9,18 +9,18 @@ ci:
repos: repos:
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 22.6.0 rev: 22.8.0
hooks: hooks:
- id: black - id: black
args: args:
- --diff - --diff
- --check - --check
- repo: https://github.com/PyCQA/flake8 - repo: https://github.com/PyCQA/flake8
rev: 5.0.2 rev: 5.0.4
hooks: hooks:
- id: flake8 - id: flake8
- repo: https://github.com/PyCQA/pylint - repo: https://github.com/PyCQA/pylint
rev: v2.13.9 rev: v2.15.2
hooks: hooks:
- id: pylint - id: pylint
files: ^(telegram|examples)/.*\.py$ files: ^(telegram|examples)/.*\.py$

View file

@ -1,6 +1,6 @@
[tool.black] [tool.black]
line-length = 99 line-length = 99
target-version = ['py37', 'py38', 'py39', 'py310'] target-version = ['py37', 'py38', 'py39', 'py310', 'py311']
[tool.isort] # black config [tool.isort] # black config
profile = "black" profile = "black"

View file

@ -246,7 +246,7 @@ class Bot(TelegramObject, AbstractAsyncContextManager):
return decorator return decorator
def _insert_defaults(self, data: Dict[str, object]) -> None: # pylint: disable=no-self-use def _insert_defaults(self, data: Dict[str, object]) -> None: # skipcq: PYL-R0201
"""This method is here to make ext.Defaults work. Because we need to be able to tell """This method is here to make ext.Defaults work. Because we need to be able to tell
e.g. `send_message(chat_id, text)` from `send_message(chat_id, text, parse_mode=None)`, the e.g. `send_message(chat_id, text)` from `send_message(chat_id, text, parse_mode=None)`, the
default values for `parse_mode` etc are not `None` but `DEFAULT_NONE`. While this *could* default values for `parse_mode` etc are not `None` but `DEFAULT_NONE`. While this *could*
@ -2724,7 +2724,7 @@ class Bot(TelegramObject, AbstractAsyncContextManager):
) )
return result # type: ignore[return-value] return result # type: ignore[return-value]
def _effective_inline_results( # pylint: disable=no-self-use def _effective_inline_results( # skipcq: PYL-R0201
self, self,
results: Union[ results: Union[
Sequence["InlineQueryResult"], Callable[[int], Optional[Sequence["InlineQueryResult"]]] Sequence["InlineQueryResult"], Callable[[int], Optional[Sequence["InlineQueryResult"]]]
@ -2781,9 +2781,7 @@ class Bot(TelegramObject, AbstractAsyncContextManager):
return effective_results, next_offset return effective_results, next_offset
@no_type_check # mypy doesn't play too well with hasattr @no_type_check # mypy doesn't play too well with hasattr
def _insert_defaults_for_ilq_results( # pylint: disable=no-self-use def _insert_defaults_for_ilq_results(self, res: "InlineQueryResult") -> None:
self, res: "InlineQueryResult"
) -> None:
"""The reason why this method exists is similar to the description of _insert_defaults """The reason why this method exists is similar to the description of _insert_defaults
The reason why we do this in rather than in _insert_defaults is because converting The reason why we do this in rather than in _insert_defaults is because converting
DEFAULT_NONE to NONE *before* calling to_dict() makes it way easier to drop None entries DEFAULT_NONE to NONE *before* calling to_dict() makes it way easier to drop None entries

View file

@ -27,7 +27,7 @@ from telegram._utils.warnings import warn
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
TO_co = TypeVar("TO_co", bound="TelegramObject", covariant=True) Tele_co = TypeVar("Tele_co", bound="TelegramObject", covariant=True)
class TelegramObject: class TelegramObject:
@ -96,7 +96,7 @@ class TelegramObject:
for key, val in state.items(): for key, val in state.items():
setattr(self, key, val) setattr(self, key, val)
def __deepcopy__(self: TO_co, memodict: dict) -> TO_co: def __deepcopy__(self: Tele_co, memodict: dict) -> Tele_co:
"""This method deepcopies the object and sets the bot on the newly created copy.""" """This method deepcopies the object and sets the bot on the newly created copy."""
bot = self._bot # Save bot so we can set it after copying bot = self._bot # Save bot so we can set it after copying
self.set_bot(None) # set to None so it is not deepcopied self.set_bot(None) # set to None so it is not deepcopied
@ -149,7 +149,7 @@ class TelegramObject:
value = getattr(self, key, None) value = getattr(self, key, None)
if value is not None: if value is not None:
if recursive and hasattr(value, "to_dict"): if recursive and hasattr(value, "to_dict"):
data[key] = value.to_dict() data[key] = value.to_dict() # pylint: disable=no-member
else: else:
data[key] = value data[key] = value
elif not recursive: elif not recursive:
@ -166,7 +166,7 @@ class TelegramObject:
return None if data is None else data.copy() return None if data is None else data.copy()
@classmethod @classmethod
def de_json(cls: Type[TO_co], data: Optional[JSONDict], bot: "Bot") -> Optional[TO_co]: def de_json(cls: Type[Tele_co], data: Optional[JSONDict], bot: "Bot") -> Optional[Tele_co]:
"""Converts JSON data to a Telegram object. """Converts JSON data to a Telegram object.
Args: Args:
@ -188,8 +188,8 @@ class TelegramObject:
@classmethod @classmethod
def de_list( def de_list(
cls: Type[TO_co], data: Optional[List[JSONDict]], bot: "Bot" cls: Type[Tele_co], data: Optional[List[JSONDict]], bot: "Bot"
) -> List[Optional[TO_co]]: ) -> List[Optional[Tele_co]]:
"""Converts JSON data to a list of Telegram objects. """Converts JSON data to a list of Telegram objects.
Args: Args:
@ -251,13 +251,13 @@ class TelegramObject:
def __eq__(self, other: object) -> bool: def __eq__(self, other: object) -> bool:
if isinstance(other, self.__class__): if isinstance(other, self.__class__):
if self._id_attrs == (): if not self._id_attrs:
warn( warn(
f"Objects of type {self.__class__.__name__} can not be meaningfully tested for" f"Objects of type {self.__class__.__name__} can not be meaningfully tested for"
" equivalence.", " equivalence.",
stacklevel=2, stacklevel=2,
) )
if other._id_attrs == (): if not other._id_attrs:
warn( warn(
f"Objects of type {other.__class__.__name__} can not be meaningfully tested" f"Objects of type {other.__class__.__name__} can not be meaningfully tested"
" for equivalence.", " for equivalence.",

View file

@ -28,6 +28,8 @@ those classes.
* Most of the constants in this module are grouped into enums. * Most of the constants in this module are grouped into enums.
""" """
# TODO: Remove this when https://github.com/PyCQA/pylint/issues/6887 is resolved.
# pylint: disable=invalid-enum-extension
__all__ = [ __all__ = [
"BOT_API_VERSION", "BOT_API_VERSION",

View file

@ -161,7 +161,7 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
return self._update_interval return self._update_interval
@update_interval.setter @update_interval.setter
def update_interval(self, value: object) -> NoReturn: # pylint: disable=no-self-use def update_interval(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to update_interval after initialization." "You can not assign a new value to update_interval after initialization."
) )

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=no-self-use
"""This module contains the CallbackContext class.""" """This module contains the CallbackContext class."""
from typing import TYPE_CHECKING, Coroutine, Dict, Generic, List, Match, NoReturn, Optional, Type from typing import TYPE_CHECKING, Coroutine, Dict, Generic, List, Match, NoReturn, Optional, Type

View file

@ -16,13 +16,12 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=no-self-use
"""This module contains the ConversationHandler.""" """This module contains the ConversationHandler."""
import asyncio import asyncio
import datetime import datetime
import logging import logging
from dataclasses import dataclass from dataclasses import dataclass
from typing import ( # pylint: disable=unused-import # for the "Any" import from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
ClassVar, ClassVar,

View file

@ -16,7 +16,6 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=no-self-use
"""This module contains the class Defaults, which allows passing default values to Application.""" """This module contains the class Defaults, which allows passing default values to Application."""
from typing import Any, Dict, NoReturn, Optional from typing import Any, Dict, NoReturn, Optional

View file

@ -34,10 +34,10 @@ from telegram.ext._utils.types import BD, CD, UD, CDCData, ConversationDict, Con
_REPLACED_KNOWN_BOT = "a known bot replaced by PTB's PicklePersistence" _REPLACED_KNOWN_BOT = "a known bot replaced by PTB's PicklePersistence"
_REPLACED_UNKNOWN_BOT = "an unknown bot replaced by PTB's PicklePersistence" _REPLACED_UNKNOWN_BOT = "an unknown bot replaced by PTB's PicklePersistence"
TO = TypeVar("TO", bound=TelegramObject) TelegramObj = TypeVar("TelegramObj", bound=TelegramObject)
def _all_subclasses(cls: Type[TO]) -> Set[Type[TO]]: def _all_subclasses(cls: Type[TelegramObj]) -> Set[Type[TelegramObj]]:
"""Gets all subclasses of the specified object, recursively. from """Gets all subclasses of the specified object, recursively. from
https://stackoverflow.com/a/3862957/9706202 https://stackoverflow.com/a/3862957/9706202
""" """
@ -45,7 +45,7 @@ def _all_subclasses(cls: Type[TO]) -> Set[Type[TO]]:
return set(subclasses).union([s for c in subclasses for s in _all_subclasses(c)]) return set(subclasses).union([s for c in subclasses for s in _all_subclasses(c)])
def _reconstruct_to(cls: Type[TO], kwargs: dict) -> TO: def _reconstruct_to(cls: Type[TelegramObj], kwargs: dict) -> TelegramObj:
""" """
This method is used for unpickling. The data, which is in the form a dictionary, is This method is used for unpickling. The data, which is in the form a dictionary, is
converted back into a class. Works mostly the same as :meth:`TelegramObject.__setstate__`. converted back into a class. Works mostly the same as :meth:`TelegramObject.__setstate__`.
@ -57,7 +57,7 @@ def _reconstruct_to(cls: Type[TO], kwargs: dict) -> TO:
return obj # type: ignore[return-value] return obj # type: ignore[return-value]
def _custom_reduction(cls: TO) -> Tuple[Callable, Tuple[Type[TO], dict]]: def _custom_reduction(cls: TelegramObj) -> Tuple[Callable, Tuple[Type[TelegramObj], dict]]:
""" """
This method is used for pickling. The bot attribute is preserved so _BotPickler().persistent_id This method is used for pickling. The bot attribute is preserved so _BotPickler().persistent_id
works as intended. works as intended.
@ -80,9 +80,9 @@ class _BotPickler(pickle.Pickler):
self.dispatch_table[obj] = _custom_reduction self.dispatch_table[obj] = _custom_reduction
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def reducer_override( # pylint: disable=no-self-use def reducer_override( # skipcq: PYL-R0201
self, obj: TO self, obj: TelegramObj
) -> Tuple[Callable, Tuple[Type[TO], dict]]: ) -> Tuple[Callable, Tuple[Type[TelegramObj], dict]]:
if not isinstance(obj, TelegramObject): if not isinstance(obj, TelegramObject):
return NotImplemented return NotImplemented

View file

@ -110,12 +110,12 @@ class TelegramHandler(tornado.web.RequestHandler):
"""Initialize for each request - that's the interface provided by tornado""" """Initialize for each request - that's the interface provided by tornado"""
# pylint: disable=attribute-defined-outside-init # pylint: disable=attribute-defined-outside-init
self.bot = bot self.bot = bot
self.update_queue = update_queue self.update_queue = update_queue # skipcq: PYL-W0201
self._logger = logging.getLogger(__name__) self._logger = logging.getLogger(__name__) # skipcq: PYL-W0201
self.secret_token = secret_token self.secret_token = secret_token # skipcq: PYL-W0201
if secret_token: if secret_token:
self._logger.debug( self._logger.debug(
"The webhook server has a secret token, " "expecting it in incoming requests now" "The webhook server has a secret token, expecting it in incoming requests now"
) )
def set_default_headers(self) -> None: def set_default_headers(self) -> None:

View file

@ -182,8 +182,7 @@ class BaseFilter:
self._name = self.__class__.__name__ if name is None else name self._name = self.__class__.__name__ if name is None else name
self._data_filter = data_filter self._data_filter = data_filter
# pylint: disable=no-self-use def check_update(self, update: Update) -> Optional[Union[bool, DataDict]]: # skipcq: PYL-R0201
def check_update(self, update: Update) -> Optional[Union[bool, DataDict]]:
"""Checks if the specified update is a message.""" """Checks if the specified update is a message."""
if ( # Only message updates should be handled. if ( # Only message updates should be handled.
update.channel_post update.channel_post