Reduce Usage of typing.Any (#2321)

* Use object instead of Any where possible

* Revert a lof of noise from the PR
This commit is contained in:
Bibo-Joshi 2021-01-30 11:38:54 +01:00 committed by GitHub
parent 40995b19fe
commit 70aba136e4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
36 changed files with 146 additions and 148 deletions

View file

@ -23,7 +23,7 @@ except ImportError:
import json # type: ignore[no-redef] import json # type: ignore[no-redef]
import warnings import warnings
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type, TypeVar from typing import TYPE_CHECKING, List, Optional, Tuple, Type, TypeVar
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
@ -36,15 +36,12 @@ TO = TypeVar('TO', bound='TelegramObject', covariant=True)
class TelegramObject: class TelegramObject:
"""Base class for most telegram objects.""" """Base class for most telegram objects."""
# def __init__(self, *args: Any, **_kwargs: Any): _id_attrs: Tuple[object, ...] = ()
# pass
_id_attrs: Tuple[Any, ...] = ()
def __str__(self) -> str: def __str__(self) -> str:
return str(self.to_dict()) return str(self.to_dict())
def __getitem__(self, item: str) -> Any: def __getitem__(self, item: str) -> object:
return self.__dict__[item] return self.__dict__[item]
@staticmethod @staticmethod

View file

@ -27,7 +27,6 @@ from datetime import datetime
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any,
Callable, Callable,
List, List,
Optional, Optional,
@ -110,11 +109,11 @@ RT = TypeVar('RT')
def log( def log(
func: Callable[..., RT], *args: Any, **kwargs: Any # pylint: disable=W0613 func: Callable[..., RT], *args: object, **kwargs: object # pylint: disable=W0613
) -> Callable[..., RT]: ) -> Callable[..., RT]:
logger = logging.getLogger(func.__module__) logger = logging.getLogger(func.__module__)
def decorator(self: 'Bot', *args: Any, **kwargs: Any) -> RT: # pylint: disable=W0613 def decorator(self: 'Bot', *args: object, **kwargs: object) -> RT: # pylint: disable=W0613
logger.debug('Entering: %s', func.__name__) logger.debug('Entering: %s', func.__name__)
result = func(*args, **kwargs) result = func(*args, **kwargs)
logger.debug(result) logger.debug(result)
@ -150,7 +149,7 @@ class Bot(TelegramObject):
""" """
def __new__(cls, *args: Any, **kwargs: Any) -> 'Bot': # pylint: disable=W0613 def __new__(cls, *args: object, **kwargs: object) -> 'Bot': # pylint: disable=W0613
# Get default values from kwargs # Get default values from kwargs
defaults = kwargs.get('defaults') defaults = kwargs.get('defaults')

View file

@ -19,7 +19,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Chat.""" """This module contains an object that represents a Telegram Chat."""
from datetime import datetime from datetime import datetime
from typing import TYPE_CHECKING, Any, List, Optional, ClassVar, Union, Tuple from typing import TYPE_CHECKING, List, Optional, ClassVar, Union, Tuple, Any
from telegram import ChatPhoto, TelegramObject, constants from telegram import ChatPhoto, TelegramObject, constants
from telegram.utils.types import JSONDict, FileInput from telegram.utils.types import JSONDict, FileInput

View file

@ -20,7 +20,7 @@
import warnings import warnings
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from copy import copy from copy import copy
from typing import Any, DefaultDict, Dict, Optional, Tuple, cast, ClassVar from typing import DefaultDict, Dict, Optional, Tuple, cast, ClassVar
from telegram import Bot from telegram import Bot
@ -75,7 +75,9 @@ class BasePersistence(ABC):
persistence class. persistence class.
""" """
def __new__(cls, *args: Any, **kwargs: Any) -> 'BasePersistence': # pylint: disable=W0613 def __new__(
cls, *args: object, **kwargs: object # pylint: disable=W0613
) -> 'BasePersistence':
instance = super().__new__(cls) instance = super().__new__(cls)
get_user_data = instance.get_user_data get_user_data = instance.get_user_data
get_chat_data = instance.get_chat_data get_chat_data = instance.get_chat_data
@ -84,13 +86,13 @@ class BasePersistence(ABC):
update_chat_data = instance.update_chat_data update_chat_data = instance.update_chat_data
update_bot_data = instance.update_bot_data update_bot_data = instance.update_bot_data
def get_user_data_insert_bot() -> DefaultDict[int, Dict[Any, Any]]: def get_user_data_insert_bot() -> DefaultDict[int, Dict[object, object]]:
return instance.insert_bot(get_user_data()) return instance.insert_bot(get_user_data())
def get_chat_data_insert_bot() -> DefaultDict[int, Dict[Any, Any]]: def get_chat_data_insert_bot() -> DefaultDict[int, Dict[object, object]]:
return instance.insert_bot(get_chat_data()) return instance.insert_bot(get_chat_data())
def get_bot_data_insert_bot() -> Dict[Any, Any]: def get_bot_data_insert_bot() -> Dict[object, object]:
return instance.insert_bot(get_bot_data()) return instance.insert_bot(get_bot_data())
def update_user_data_replace_bot(user_id: int, data: Dict) -> None: def update_user_data_replace_bot(user_id: int, data: Dict) -> None:
@ -146,7 +148,7 @@ class BasePersistence(ABC):
return cls._replace_bot(obj, {}) return cls._replace_bot(obj, {})
@classmethod @classmethod
def _replace_bot(cls, obj: object, memo: Dict[int, Any]) -> object: # pylint: disable=R0911 def _replace_bot(cls, obj: object, memo: Dict[int, object]) -> object: # pylint: disable=R0911
obj_id = id(obj) obj_id = id(obj)
if obj_id in memo: if obj_id in memo:
return memo[obj_id] return memo[obj_id]
@ -223,7 +225,7 @@ class BasePersistence(ABC):
""" """
return self._insert_bot(obj, {}) return self._insert_bot(obj, {})
def _insert_bot(self, obj: object, memo: Dict[int, Any]) -> object: # pylint: disable=R0911 def _insert_bot(self, obj: object, memo: Dict[int, object]) -> object: # pylint: disable=R0911
obj_id = id(obj) obj_id = id(obj)
if obj_id in memo: if obj_id in memo:
return memo[obj_id] return memo[obj_id]
@ -288,7 +290,7 @@ class BasePersistence(ABC):
return obj return obj
@abstractmethod @abstractmethod
def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]: def get_user_data(self) -> DefaultDict[int, Dict[object, object]]:
""" "Will be called by :class:`telegram.ext.Dispatcher` upon creation with a """ "Will be called by :class:`telegram.ext.Dispatcher` upon creation with a
persistence object. It should return the ``user_data`` if stored, or an empty persistence object. It should return the ``user_data`` if stored, or an empty
``defaultdict(dict)``. ``defaultdict(dict)``.
@ -298,7 +300,7 @@ class BasePersistence(ABC):
""" """
@abstractmethod @abstractmethod
def get_chat_data(self) -> DefaultDict[int, Dict[Any, Any]]: def get_chat_data(self) -> DefaultDict[int, Dict[object, object]]:
""" "Will be called by :class:`telegram.ext.Dispatcher` upon creation with a """ "Will be called by :class:`telegram.ext.Dispatcher` upon creation with a
persistence object. It should return the ``chat_data`` if stored, or an empty persistence object. It should return the ``chat_data`` if stored, or an empty
``defaultdict(dict)``. ``defaultdict(dict)``.
@ -308,7 +310,7 @@ class BasePersistence(ABC):
""" """
@abstractmethod @abstractmethod
def get_bot_data(self) -> Dict[Any, Any]: def get_bot_data(self) -> Dict[object, object]:
""" "Will be called by :class:`telegram.ext.Dispatcher` upon creation with a """ "Will be called by :class:`telegram.ext.Dispatcher` upon creation with a
persistence object. It should return the ``bot_data`` if stored, or an empty persistence object. It should return the ``bot_data`` if stored, or an empty
:obj:`dict`. :obj:`dict`.

View file

@ -19,7 +19,7 @@
# pylint: disable=R0201 # pylint: disable=R0201
"""This module contains the CallbackContext class.""" """This module contains the CallbackContext class."""
from queue import Queue from queue import Queue
from typing import TYPE_CHECKING, Any, Dict, List, Match, NoReturn, Optional, Tuple, Union from typing import TYPE_CHECKING, Dict, List, Match, NoReturn, Optional, Tuple, Union
from telegram import Update from telegram import Update
@ -98,14 +98,14 @@ class CallbackContext:
) )
self._dispatcher = dispatcher self._dispatcher = dispatcher
self._bot_data = dispatcher.bot_data self._bot_data = dispatcher.bot_data
self._chat_data: Optional[Dict[Any, Any]] = None self._chat_data: Optional[Dict[object, object]] = None
self._user_data: Optional[Dict[Any, Any]] = None self._user_data: Optional[Dict[object, object]] = None
self.args: Optional[List[str]] = None self.args: Optional[List[str]] = None
self.matches: Optional[List[Match]] = None self.matches: Optional[List[Match]] = None
self.error: Optional[Exception] = None self.error: Optional[Exception] = None
self.job: Optional['Job'] = None self.job: Optional['Job'] = None
self.async_args: Optional[Union[List, Tuple]] = None self.async_args: Optional[Union[List, Tuple]] = None
self.async_kwargs: Optional[Dict[str, Any]] = None self.async_kwargs: Optional[Dict[str, object]] = None
@property @property
def dispatcher(self) -> 'Dispatcher': def dispatcher(self) -> 'Dispatcher':
@ -117,7 +117,7 @@ class CallbackContext:
return self._bot_data return self._bot_data
@bot_data.setter @bot_data.setter
def bot_data(self, value: Any) -> NoReturn: def bot_data(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to bot_data, see " "https://git.io/fjxKe" "You can not assign a new value to bot_data, see " "https://git.io/fjxKe"
) )
@ -127,7 +127,7 @@ class CallbackContext:
return self._chat_data return self._chat_data
@chat_data.setter @chat_data.setter
def chat_data(self, value: Any) -> NoReturn: def chat_data(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to chat_data, see " "https://git.io/fjxKe" "You can not assign a new value to chat_data, see " "https://git.io/fjxKe"
) )
@ -137,7 +137,7 @@ class CallbackContext:
return self._user_data return self._user_data
@user_data.setter @user_data.setter
def user_data(self, value: Any) -> NoReturn: def user_data(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to user_data, see " "https://git.io/fjxKe" "You can not assign a new value to user_data, see " "https://git.io/fjxKe"
) )
@ -149,7 +149,7 @@ class CallbackContext:
error: Exception, error: Exception,
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
async_args: Union[List, Tuple] = None, async_args: Union[List, Tuple] = None,
async_kwargs: Dict[str, Any] = None, async_kwargs: Dict[str, object] = None,
) -> 'CallbackContext': ) -> 'CallbackContext':
self = cls.from_update(update, dispatcher) self = cls.from_update(update, dispatcher)
self.error = error self.error = error
@ -177,7 +177,7 @@ class CallbackContext:
self.job = job self.job = job
return self return self
def update(self, data: Dict[str, Any]) -> None: def update(self, data: Dict[str, object]) -> None:
self.__dict__.update(data) self.__dict__.update(data)
@property @property

View file

@ -21,7 +21,6 @@
import re import re
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any,
Callable, Callable,
Dict, Dict,
Match, Match,
@ -148,7 +147,7 @@ class CallbackQueryHandler(Handler[Update]):
self.pass_groups = pass_groups self.pass_groups = pass_groups
self.pass_groupdict = pass_groupdict self.pass_groupdict = pass_groupdict
def check_update(self, update: Any) -> Optional[Union[bool, object]]: def check_update(self, update: object) -> Optional[Union[bool, object]]:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:
@ -173,7 +172,7 @@ class CallbackQueryHandler(Handler[Update]):
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
update: Update = None, update: Update = None,
check_result: Union[bool, Match] = None, check_result: Union[bool, Match] = None,
) -> Dict[str, Any]: ) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result) optional_args = super().collect_optional_args(dispatcher, update, check_result)
if self.pattern: if self.pattern:
check_result = cast(Match, check_result) check_result = cast(Match, check_result)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the ChosenInlineResultHandler class.""" """This module contains the ChosenInlineResultHandler class."""
from typing import Optional, TypeVar, Union, Any from typing import Optional, TypeVar, Union
from telegram import Update from telegram import Update
@ -85,7 +85,7 @@ class ChosenInlineResultHandler(Handler[Update]):
""" """
def check_update(self, update: Any) -> Optional[Union[bool, object]]: def check_update(self, update: object) -> Optional[Union[bool, object]]:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:

View file

@ -19,7 +19,7 @@
"""This module contains the CommandHandler and PrefixHandler classes.""" """This module contains the CommandHandler and PrefixHandler classes."""
import re import re
import warnings import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union from typing import TYPE_CHECKING, Callable, Dict, List, Optional, Tuple, TypeVar, Union
from telegram import MessageEntity, Update from telegram import MessageEntity, Update
from telegram.ext import BaseFilter, Filters from telegram.ext import BaseFilter, Filters
@ -177,7 +177,7 @@ class CommandHandler(Handler[Update]):
self.pass_args = pass_args self.pass_args = pass_args
def check_update( def check_update(
self, update: Any self, update: object
) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, Dict]]]]]: ) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, Dict]]]]]:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
@ -220,7 +220,7 @@ class CommandHandler(Handler[Update]):
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
update: Update = None, update: Update = None,
check_result: Optional[Union[bool, Tuple[List[str], Optional[bool]]]] = None, check_result: Optional[Union[bool, Tuple[List[str], Optional[bool]]]] = None,
) -> Dict[str, Any]: ) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update) optional_args = super().collect_optional_args(dispatcher, update)
if self.pass_args and isinstance(check_result, tuple): if self.pass_args and isinstance(check_result, tuple):
optional_args['args'] = check_result[0] optional_args['args'] = check_result[0]
@ -415,7 +415,7 @@ class PrefixHandler(CommandHandler):
self._commands = [x.lower() + y.lower() for x in self.prefix for y in self.command] self._commands = [x.lower() + y.lower() for x in self.prefix for y in self.command]
def check_update( def check_update(
self, update: Update self, update: object
) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, Dict]]]]]: ) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, Dict]]]]]:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.

View file

@ -22,7 +22,7 @@
import logging import logging
import warnings import warnings
from threading import Lock from threading import Lock
from typing import TYPE_CHECKING, Any, Dict, List, NoReturn, Optional, Tuple, cast, ClassVar from typing import TYPE_CHECKING, Dict, List, NoReturn, Optional, Tuple, cast, ClassVar
from telegram import Update from telegram import Update
from telegram.ext import ( from telegram.ext import (
@ -286,7 +286,7 @@ class ConversationHandler(Handler[Update]):
return self._entry_points return self._entry_points
@entry_points.setter @entry_points.setter
def entry_points(self, value: Any) -> NoReturn: def entry_points(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to entry_points after initialization.') raise ValueError('You can not assign a new value to entry_points after initialization.')
@property @property
@ -294,7 +294,7 @@ class ConversationHandler(Handler[Update]):
return self._states return self._states
@states.setter @states.setter
def states(self, value: Any) -> NoReturn: def states(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to states after initialization.') raise ValueError('You can not assign a new value to states after initialization.')
@property @property
@ -302,7 +302,7 @@ class ConversationHandler(Handler[Update]):
return self._fallbacks return self._fallbacks
@fallbacks.setter @fallbacks.setter
def fallbacks(self, value: Any) -> NoReturn: def fallbacks(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to fallbacks after initialization.') raise ValueError('You can not assign a new value to fallbacks after initialization.')
@property @property
@ -310,7 +310,7 @@ class ConversationHandler(Handler[Update]):
return self._allow_reentry return self._allow_reentry
@allow_reentry.setter @allow_reentry.setter
def allow_reentry(self, value: Any) -> NoReturn: def allow_reentry(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to allow_reentry after initialization.') raise ValueError('You can not assign a new value to allow_reentry after initialization.')
@property @property
@ -318,7 +318,7 @@ class ConversationHandler(Handler[Update]):
return self._per_user return self._per_user
@per_user.setter @per_user.setter
def per_user(self, value: Any) -> NoReturn: def per_user(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to per_user after initialization.') raise ValueError('You can not assign a new value to per_user after initialization.')
@property @property
@ -326,7 +326,7 @@ class ConversationHandler(Handler[Update]):
return self._per_chat return self._per_chat
@per_chat.setter @per_chat.setter
def per_chat(self, value: Any) -> NoReturn: def per_chat(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to per_chat after initialization.') raise ValueError('You can not assign a new value to per_chat after initialization.')
@property @property
@ -334,7 +334,7 @@ class ConversationHandler(Handler[Update]):
return self._per_message return self._per_message
@per_message.setter @per_message.setter
def per_message(self, value: Any) -> NoReturn: def per_message(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to per_message after initialization.') raise ValueError('You can not assign a new value to per_message after initialization.')
@property @property
@ -342,7 +342,7 @@ class ConversationHandler(Handler[Update]):
return self._conversation_timeout return self._conversation_timeout
@conversation_timeout.setter @conversation_timeout.setter
def conversation_timeout(self, value: Any) -> NoReturn: def conversation_timeout(self, value: object) -> NoReturn:
raise ValueError( raise ValueError(
'You can not assign a new value to conversation_timeout after ' 'initialization.' 'You can not assign a new value to conversation_timeout after ' 'initialization.'
) )
@ -352,7 +352,7 @@ class ConversationHandler(Handler[Update]):
return self._name return self._name
@name.setter @name.setter
def name(self, value: Any) -> NoReturn: def name(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to name after initialization.') raise ValueError('You can not assign a new value to name after initialization.')
@property @property
@ -360,7 +360,7 @@ class ConversationHandler(Handler[Update]):
return self._map_to_parent return self._map_to_parent
@map_to_parent.setter @map_to_parent.setter
def map_to_parent(self, value: Any) -> NoReturn: def map_to_parent(self, value: object) -> NoReturn:
raise ValueError('You can not assign a new value to map_to_parent after initialization.') raise ValueError('You can not assign a new value to map_to_parent after initialization.')
@property @property
@ -409,7 +409,7 @@ class ConversationHandler(Handler[Update]):
return tuple(key) return tuple(key)
def check_update(self, update: Any) -> CheckUpdateType: # pylint: disable=R0911 def check_update(self, update: object) -> CheckUpdateType: # pylint: disable=R0911
""" """
Determines whether an update should be handled by this conversationhandler, and if so in Determines whether an update should be handled by this conversationhandler, and if so in
which state the conversation currently is. which state the conversation currently is.

View file

@ -18,7 +18,7 @@
# 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=R0201, E0401 # pylint: disable=R0201, E0401
"""This module contains the class Defaults, which allows to pass default values to Updater.""" """This module contains the class Defaults, which allows to pass default values to Updater."""
from typing import Any, NoReturn, Optional, Union from typing import NoReturn, Optional, Union
import pytz import pytz
@ -100,7 +100,7 @@ class Defaults:
return self._parse_mode return self._parse_mode
@parse_mode.setter @parse_mode.setter
def parse_mode(self, value: Any) -> NoReturn: def parse_mode(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to defaults after because it would " "You can not assign a new value to defaults after because it would "
"not have any effect." "not have any effect."
@ -111,7 +111,7 @@ class Defaults:
return self._disable_notification return self._disable_notification
@disable_notification.setter @disable_notification.setter
def disable_notification(self, value: Any) -> NoReturn: def disable_notification(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to defaults after because it would " "You can not assign a new value to defaults after because it would "
"not have any effect." "not have any effect."
@ -122,7 +122,7 @@ class Defaults:
return self._disable_web_page_preview return self._disable_web_page_preview
@disable_web_page_preview.setter @disable_web_page_preview.setter
def disable_web_page_preview(self, value: Any) -> NoReturn: def disable_web_page_preview(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to defaults after because it would " "You can not assign a new value to defaults after because it would "
"not have any effect." "not have any effect."
@ -133,7 +133,7 @@ class Defaults:
return self._allow_sending_without_reply return self._allow_sending_without_reply
@allow_sending_without_reply.setter @allow_sending_without_reply.setter
def allow_sending_without_reply(self, value: Any) -> NoReturn: def allow_sending_without_reply(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to defaults after because it would " "You can not assign a new value to defaults after because it would "
"not have any effect." "not have any effect."
@ -144,7 +144,7 @@ class Defaults:
return self._timeout return self._timeout
@timeout.setter @timeout.setter
def timeout(self, value: Any) -> NoReturn: def timeout(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to defaults after because it would " "You can not assign a new value to defaults after because it would "
"not have any effect." "not have any effect."
@ -155,7 +155,7 @@ class Defaults:
return self._quote return self._quote
@quote.setter @quote.setter
def quote(self, value: Any) -> NoReturn: def quote(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to defaults after because it would " "You can not assign a new value to defaults after because it would "
"not have any effect." "not have any effect."
@ -166,7 +166,7 @@ class Defaults:
return self._tzinfo return self._tzinfo
@tzinfo.setter @tzinfo.setter
def tzinfo(self, value: Any) -> NoReturn: def tzinfo(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to defaults after because it would " "You can not assign a new value to defaults after because it would "
"not have any effect." "not have any effect."
@ -177,7 +177,7 @@ class Defaults:
return self._run_async return self._run_async
@run_async.setter @run_async.setter
def run_async(self, value: Any) -> NoReturn: def run_async(self, value: object) -> NoReturn:
raise AttributeError( raise AttributeError(
"You can not assign a new value to defaults after because it would " "You can not assign a new value to defaults after because it would "
"not have any effect." "not have any effect."

View file

@ -19,7 +19,7 @@
"""This module contains the DictPersistence class.""" """This module contains the DictPersistence class."""
from copy import deepcopy from copy import deepcopy
from typing import Any, DefaultDict, Dict, Optional, Tuple from typing import DefaultDict, Dict, Optional, Tuple
from collections import defaultdict from collections import defaultdict
from telegram.utils.helpers import ( from telegram.utils.helpers import (
@ -169,7 +169,7 @@ class DictPersistence(BasePersistence):
return json.dumps(self.bot_data) return json.dumps(self.bot_data)
@property @property
def conversations(self) -> Optional[Dict[str, Dict[Tuple, Any]]]: def conversations(self) -> Optional[Dict[str, Dict[Tuple, object]]]:
""":obj:`dict`: The conversations as a dict.""" """:obj:`dict`: The conversations as a dict."""
return self._conversations return self._conversations
@ -180,7 +180,7 @@ class DictPersistence(BasePersistence):
return self._conversations_json return self._conversations_json
return encode_conversations_to_json(self.conversations) # type: ignore[arg-type] return encode_conversations_to_json(self.conversations) # type: ignore[arg-type]
def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]: def get_user_data(self) -> DefaultDict[int, Dict[object, object]]:
"""Returns the user_data created from the ``user_data_json`` or an empty """Returns the user_data created from the ``user_data_json`` or an empty
:obj:`defaultdict`. :obj:`defaultdict`.
@ -193,7 +193,7 @@ class DictPersistence(BasePersistence):
self._user_data = defaultdict(dict) self._user_data = defaultdict(dict)
return deepcopy(self.user_data) # type: ignore[arg-type] return deepcopy(self.user_data) # type: ignore[arg-type]
def get_chat_data(self) -> DefaultDict[int, Dict[Any, Any]]: def get_chat_data(self) -> DefaultDict[int, Dict[object, object]]:
"""Returns the chat_data created from the ``chat_data_json`` or an empty """Returns the chat_data created from the ``chat_data_json`` or an empty
:obj:`defaultdict`. :obj:`defaultdict`.
@ -206,7 +206,7 @@ class DictPersistence(BasePersistence):
self._chat_data = defaultdict(dict) self._chat_data = defaultdict(dict)
return deepcopy(self.chat_data) # type: ignore[arg-type] return deepcopy(self.chat_data) # type: ignore[arg-type]
def get_bot_data(self) -> Dict[Any, Any]: def get_bot_data(self) -> Dict[object, object]:
"""Returns the bot_data created from the ``bot_data_json`` or an empty :obj:`dict`. """Returns the bot_data created from the ``bot_data_json`` or an empty :obj:`dict`.
Returns: Returns:

View file

@ -26,7 +26,7 @@ from functools import wraps
from queue import Empty, Queue from queue import Empty, Queue
from threading import BoundedSemaphore, Event, Lock, Thread, current_thread from threading import BoundedSemaphore, Event, Lock, Thread, current_thread
from time import sleep from time import sleep
from typing import TYPE_CHECKING, Any, Callable, DefaultDict, Dict, List, Optional, Set, Union from typing import TYPE_CHECKING, Callable, DefaultDict, Dict, List, Optional, Set, Union
from uuid import uuid4 from uuid import uuid4
from telegram import TelegramError, Update from telegram import TelegramError, Update
@ -45,8 +45,8 @@ DEFAULT_GROUP: int = 0
def run_async( def run_async(
func: Callable[[Update, CallbackContext], Any] func: Callable[[Update, CallbackContext], object]
) -> Callable[[Update, CallbackContext], Any]: ) -> Callable[[Update, CallbackContext], object]:
""" """
Function decorator that will run the function in a new thread. Function decorator that will run the function in a new thread.
@ -64,7 +64,7 @@ def run_async(
""" """
@wraps(func) @wraps(func)
def async_func(*args: Any, **kwargs: Any) -> Any: def async_func(*args: object, **kwargs: object) -> object:
warnings.warn( warnings.warn(
'The @run_async decorator is deprecated. Use the `run_async` parameter of ' 'The @run_async decorator is deprecated. Use the `run_async` parameter of '
'your Handler or `Dispatcher.run_async` instead.', 'your Handler or `Dispatcher.run_async` instead.',
@ -162,8 +162,8 @@ class Dispatcher:
stacklevel=3, stacklevel=3,
) )
self.user_data: DefaultDict[int, Dict[Any, Any]] = defaultdict(dict) self.user_data: DefaultDict[int, Dict[object, object]] = defaultdict(dict)
self.chat_data: DefaultDict[int, Dict[Any, Any]] = defaultdict(dict) self.chat_data: DefaultDict[int, Dict[object, object]] = defaultdict(dict)
self.bot_data = {} self.bot_data = {}
self.persistence: Optional[BasePersistence] = None self.persistence: Optional[BasePersistence] = None
self._update_persistence_lock = Lock() self._update_persistence_lock = Lock()
@ -287,7 +287,7 @@ class Dispatcher:
self.logger.exception('An uncaught error was raised while handling the error.') self.logger.exception('An uncaught error was raised while handling the error.')
def run_async( def run_async(
self, func: Callable[..., Any], *args: Any, update: Any = None, **kwargs: Any self, func: Callable[..., object], *args: object, update: object = None, **kwargs: object
) -> Promise: ) -> Promise:
""" """
Queue a function (with given args/kwargs) to be run asynchronously. Exceptions raised Queue a function (with given args/kwargs) to be run asynchronously. Exceptions raised
@ -316,11 +316,11 @@ class Dispatcher:
def _run_async( def _run_async(
self, self,
func: Callable[..., Any], func: Callable[..., object],
*args: Any, *args: object,
update: Any = None, update: object = None,
error_handling: bool = True, error_handling: bool = True,
**kwargs: Any, **kwargs: object,
) -> Promise: ) -> Promise:
# TODO: Remove error_handling parameter once we drop the @run_async decorator # TODO: Remove error_handling parameter once we drop the @run_async decorator
promise = Promise(func, args, kwargs, update=update, error_handling=error_handling) promise = Promise(func, args, kwargs, update=update, error_handling=error_handling)
@ -402,7 +402,7 @@ class Dispatcher:
def has_running_threads(self) -> bool: def has_running_threads(self) -> bool:
return self.running or bool(self.__async_threads) return self.running or bool(self.__async_threads)
def process_update(self, update: Any) -> None: def process_update(self, update: object) -> None:
"""Processes a single update and updates the persistence. """Processes a single update and updates the persistence.
Note: Note:
@ -530,7 +530,7 @@ class Dispatcher:
del self.handlers[group] del self.handlers[group]
self.groups.remove(group) self.groups.remove(group)
def update_persistence(self, update: Any = None) -> None: def update_persistence(self, update: object = None) -> None:
"""Update :attr:`user_data`, :attr:`chat_data` and :attr:`bot_data` in :attr:`persistence`. """Update :attr:`user_data`, :attr:`chat_data` and :attr:`bot_data` in :attr:`persistence`.
Args: Args:
@ -540,7 +540,7 @@ class Dispatcher:
with self._update_persistence_lock: with self._update_persistence_lock:
self.__update_persistence(update) self.__update_persistence(update)
def __update_persistence(self, update: Any = None) -> None: def __update_persistence(self, update: object = None) -> None:
if self.persistence: if self.persistence:
# We use list() here in order to decouple chat_ids from self.chat_data, as dict view # We use list() here in order to decouple chat_ids from self.chat_data, as dict view
# objects will change, when the dict does and we want to loop over chat_ids # objects will change, when the dict does and we want to loop over chat_ids
@ -601,7 +601,7 @@ class Dispatcher:
def add_error_handler( def add_error_handler(
self, self,
callback: Callable[[Any, CallbackContext], None], callback: Callable[[object, CallbackContext], None],
run_async: Union[bool, DefaultValue] = DEFAULT_FALSE, # pylint: disable=W0621 run_async: Union[bool, DefaultValue] = DEFAULT_FALSE, # pylint: disable=W0621
) -> None: ) -> None:
"""Registers an error handler in the Dispatcher. This handler will receive every error """Registers an error handler in the Dispatcher. This handler will receive every error
@ -637,7 +637,7 @@ class Dispatcher:
self.error_handlers[callback] = run_async self.error_handlers[callback] = run_async
def remove_error_handler(self, callback: Callable[[Any, CallbackContext], None]) -> None: def remove_error_handler(self, callback: Callable[[object, CallbackContext], None]) -> None:
"""Removes an error handler. """Removes an error handler.
Args: Args:
@ -647,12 +647,12 @@ class Dispatcher:
self.error_handlers.pop(callback, None) self.error_handlers.pop(callback, None)
def dispatch_error( def dispatch_error(
self, update: Optional[Any], error: Exception, promise: Promise = None self, update: Optional[object], error: Exception, promise: Promise = None
) -> None: ) -> None:
"""Dispatches an error. """Dispatches an error.
Args: Args:
update (:obj:`Any` | :class:`telegram.Update`): The update that caused the error. update (:obj:`object` | :class:`telegram.Update`): The update that caused the error.
error (:obj:`Exception`): The error that was raised. error (:obj:`Exception`): The error that was raised.
promise (:class:`telegram.utils.Promise`, optional): The promise whose pooled function promise (:class:`telegram.utils.Promise`, optional): The promise whose pooled function
raised the error. raised the error.

View file

@ -107,7 +107,7 @@ class Handler(Generic[UT], ABC):
self.run_async = run_async self.run_async = run_async
@abstractmethod @abstractmethod
def check_update(self, update: Any) -> Optional[Union[bool, object]]: def check_update(self, update: object) -> Optional[Union[bool, object]]:
""" """
This method is called to determine if an update should be handled by This method is called to determine if an update should be handled by
this handler instance. It should always be overridden. this handler instance. It should always be overridden.
@ -188,7 +188,7 @@ class Handler(Generic[UT], ABC):
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
update: UT = None, update: UT = None,
check_result: Any = None, # pylint: disable=W0613 check_result: Any = None, # pylint: disable=W0613
) -> Dict[str, Any]: ) -> Dict[str, object]:
""" """
Prepares the optional arguments. If the handler has additional optional args, Prepares the optional arguments. If the handler has additional optional args,
it should subclass this method, but remember to call this super method. it should subclass this method, but remember to call this super method.
@ -202,7 +202,7 @@ class Handler(Generic[UT], ABC):
check_result: The result from check_update check_result: The result from check_update
""" """
optional_args: Dict[str, Any] = dict() optional_args: Dict[str, object] = dict()
if self.pass_update_queue: if self.pass_update_queue:
optional_args['update_queue'] = dispatcher.update_queue optional_args['update_queue'] = dispatcher.update_queue

View file

@ -20,7 +20,6 @@
import re import re
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any,
Callable, Callable,
Dict, Dict,
Match, Match,
@ -147,7 +146,7 @@ class InlineQueryHandler(Handler[Update]):
self.pass_groups = pass_groups self.pass_groups = pass_groups
self.pass_groupdict = pass_groupdict self.pass_groupdict = pass_groupdict
def check_update(self, update: Any) -> Optional[Union[bool, Match]]: def check_update(self, update: object) -> Optional[Union[bool, Match]]:
""" """
Determines whether an update should be passed to this handlers :attr:`callback`. Determines whether an update should be passed to this handlers :attr:`callback`.
@ -174,7 +173,7 @@ class InlineQueryHandler(Handler[Update]):
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
update: Update = None, update: Update = None,
check_result: Optional[Union[bool, Match]] = None, check_result: Optional[Union[bool, Match]] = None,
) -> Dict[str, Any]: ) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result) optional_args = super().collect_optional_args(dispatcher, update, check_result)
if self.pattern: if self.pattern:
check_result = cast(Match, check_result) check_result = cast(Match, check_result)

View file

@ -21,13 +21,14 @@
import datetime import datetime
import logging import logging
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, Union, cast, overload from typing import TYPE_CHECKING, Callable, List, Optional, Tuple, Union, cast, overload
import pytz import pytz
from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, JobEvent from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, JobEvent
from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.combining import OrTrigger from apscheduler.triggers.combining import OrTrigger
from apscheduler.triggers.cron import CronTrigger from apscheduler.triggers.cron import CronTrigger
from apscheduler.job import Job as APSJob
from telegram.ext.callbackcontext import CallbackContext from telegram.ext.callbackcontext import CallbackContext
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
@ -35,6 +36,7 @@ from telegram.utils.types import JSONDict
if TYPE_CHECKING: if TYPE_CHECKING:
from telegram import Bot from telegram import Bot
from telegram.ext import Dispatcher from telegram.ext import Dispatcher
import apscheduler.job # noqa: F401
class Days: class Days:
@ -551,7 +553,7 @@ class Job:
context: object = None, context: object = None,
name: str = None, name: str = None,
job_queue: JobQueue = None, job_queue: JobQueue = None,
job: 'Job' = None, job: APSJob = None,
): ):
self.callback = callback self.callback = callback
@ -562,7 +564,7 @@ class Job:
self._removed = False self._removed = False
self._enabled = False self._enabled = False
self.job = cast('Job', job) self.job = cast(APSJob, job)
def run(self, dispatcher: 'Dispatcher') -> None: def run(self, dispatcher: 'Dispatcher') -> None:
"""Executes the callback function independently of the jobs schedule.""" """Executes the callback function independently of the jobs schedule."""
@ -618,7 +620,7 @@ class Job:
return self.job.next_run_time return self.job.next_run_time
@classmethod @classmethod
def from_aps_job(cls, job: 'Job', job_queue: JobQueue) -> 'Job': def from_aps_job(cls, job: APSJob, job_queue: JobQueue) -> 'Job':
# context based callbacks # context based callbacks
if len(job.args) == 1: if len(job.args) == 1:
context = job.args[0].job.context context = job.args[0].job.context
@ -626,7 +628,7 @@ class Job:
context = job.args[1].context context = job.args[1].context
return cls(job.func, context=context, name=job.name, job_queue=job_queue, job=job) return cls(job.func, context=context, name=job.name, job_queue=job_queue, job=job)
def __getattr__(self, item: str) -> Any: def __getattr__(self, item: str) -> object:
return getattr(self.job, item) return getattr(self.job, item)
def __lt__(self, other: object) -> bool: def __lt__(self, other: object) -> bool:

View file

@ -19,7 +19,7 @@
# TODO: Remove allow_edited # TODO: Remove allow_edited
"""This module contains the MessageHandler class.""" """This module contains the MessageHandler class."""
import warnings import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar, Union from typing import TYPE_CHECKING, Callable, Dict, Optional, TypeVar, Union
from telegram import Update from telegram import Update
from telegram.ext import BaseFilter, Filters from telegram.ext import BaseFilter, Filters
@ -179,7 +179,7 @@ class MessageHandler(Handler[Update]):
Filters.update.edited_message | Filters.update.edited_channel_post Filters.update.edited_message | Filters.update.edited_channel_post
) )
def check_update(self, update: Any) -> Optional[Union[bool, Dict[str, Any]]]: def check_update(self, update: object) -> Optional[Union[bool, Dict[str, object]]]:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:
@ -198,7 +198,7 @@ class MessageHandler(Handler[Update]):
context: 'CallbackContext', context: 'CallbackContext',
update: Update, update: Update,
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
check_result: Optional[Union[bool, Dict[str, Any]]], check_result: Optional[Union[bool, Dict[str, object]]],
) -> None: ) -> None:
if isinstance(check_result, dict): if isinstance(check_result, dict):
context.update(check_result) context.update(check_result)

View file

@ -24,7 +24,7 @@ import functools
import queue as q import queue as q
import threading import threading
import time import time
from typing import TYPE_CHECKING, Any, Callable, List, NoReturn from typing import TYPE_CHECKING, Callable, List, NoReturn
from telegram.utils.promise import Promise from telegram.utils.promise import Promise
@ -153,7 +153,7 @@ class DelayQueue(threading.Thread):
raise exc raise exc
def __call__(self, func: Callable, *args: Any, **kwargs: Any) -> None: def __call__(self, func: Callable, *args: object, **kwargs: object) -> None:
"""Used to process callbacks in throughput-limiting thread through queue. """Used to process callbacks in throughput-limiting thread through queue.
Args: Args:
@ -300,7 +300,7 @@ def queuedmessage(method: Callable) -> Callable:
""" """
@functools.wraps(method) @functools.wraps(method)
def wrapped(self: 'Bot', *args: Any, **kwargs: Any) -> Any: def wrapped(self: 'Bot', *args: object, **kwargs: object) -> object:
# pylint: disable=W0212 # pylint: disable=W0212
queued = kwargs.pop( queued = kwargs.pop(
'queued', self._is_messages_queued_default # type: ignore[attr-defined] 'queued', self._is_messages_queued_default # type: ignore[attr-defined]

View file

@ -93,7 +93,7 @@ class PicklePersistence(BasePersistence):
self.user_data: Optional[DefaultDict[int, Dict]] = None self.user_data: Optional[DefaultDict[int, Dict]] = None
self.chat_data: Optional[DefaultDict[int, Dict]] = None self.chat_data: Optional[DefaultDict[int, Dict]] = None
self.bot_data: Optional[Dict] = None self.bot_data: Optional[Dict] = None
self.conversations: Optional[Dict[str, Dict[Tuple, Any]]] = None self.conversations: Optional[Dict[str, Dict[Tuple, object]]] = None
def load_singlefile(self) -> None: def load_singlefile(self) -> None:
try: try:
@ -138,11 +138,11 @@ class PicklePersistence(BasePersistence):
pickle.dump(data, file) pickle.dump(data, file)
@staticmethod @staticmethod
def dump_file(filename: str, data: Any) -> None: def dump_file(filename: str, data: object) -> None:
with open(filename, "wb") as file: with open(filename, "wb") as file:
pickle.dump(data, file) pickle.dump(data, file)
def get_user_data(self) -> DefaultDict[int, Dict[Any, Any]]: def get_user_data(self) -> DefaultDict[int, Dict[object, object]]:
"""Returns the user_data from the pickle file if it exists or an empty :obj:`defaultdict`. """Returns the user_data from the pickle file if it exists or an empty :obj:`defaultdict`.
Returns: Returns:
@ -162,7 +162,7 @@ class PicklePersistence(BasePersistence):
self.load_singlefile() self.load_singlefile()
return deepcopy(self.user_data) # type: ignore[arg-type] return deepcopy(self.user_data) # type: ignore[arg-type]
def get_chat_data(self) -> DefaultDict[int, Dict[Any, Any]]: def get_chat_data(self) -> DefaultDict[int, Dict[object, object]]:
"""Returns the chat_data from the pickle file if it exists or an empty :obj:`defaultdict`. """Returns the chat_data from the pickle file if it exists or an empty :obj:`defaultdict`.
Returns: Returns:
@ -182,7 +182,7 @@ class PicklePersistence(BasePersistence):
self.load_singlefile() self.load_singlefile()
return deepcopy(self.chat_data) # type: ignore[arg-type] return deepcopy(self.chat_data) # type: ignore[arg-type]
def get_bot_data(self) -> Dict[Any, Any]: def get_bot_data(self) -> Dict[object, object]:
"""Returns the bot_data from the pickle file if it exists or an empty :obj:`dict`. """Returns the bot_data from the pickle file if it exists or an empty :obj:`dict`.
Returns: Returns:

View file

@ -17,7 +17,7 @@
# 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/].
"""This module contains the PollAnswerHandler class.""" """This module contains the PollAnswerHandler class."""
from typing import Any
from telegram import Update from telegram import Update
@ -82,7 +82,7 @@ class PollAnswerHandler(Handler[Update]):
""" """
def check_update(self, update: Any) -> bool: def check_update(self, update: object) -> bool:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:

View file

@ -17,7 +17,7 @@
# 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/].
"""This module contains the PollHandler classes.""" """This module contains the PollHandler classes."""
from typing import Any
from telegram import Update from telegram import Update
@ -82,7 +82,7 @@ class PollHandler(Handler[Update]):
""" """
def check_update(self, update: Any) -> bool: def check_update(self, update: object) -> bool:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:

View file

@ -17,7 +17,7 @@
# 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/].
"""This module contains the PreCheckoutQueryHandler class.""" """This module contains the PreCheckoutQueryHandler class."""
from typing import Any
from telegram import Update from telegram import Update
@ -82,7 +82,7 @@ class PreCheckoutQueryHandler(Handler[Update]):
""" """
def check_update(self, update: Any) -> bool: def check_update(self, update: object) -> bool:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:

View file

@ -20,7 +20,7 @@
"""This module contains the RegexHandler class.""" """This module contains the RegexHandler class."""
import warnings import warnings
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Pattern, TypeVar, Union from typing import TYPE_CHECKING, Callable, Dict, Optional, Pattern, TypeVar, Union, Any
from telegram import Update from telegram import Update
from telegram.ext import Filters, MessageHandler from telegram.ext import Filters, MessageHandler
@ -149,7 +149,7 @@ class RegexHandler(MessageHandler):
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
update: Update = None, update: Update = None,
check_result: Optional[Union[bool, Dict[str, Any]]] = None, check_result: Optional[Union[bool, Dict[str, Any]]] = None,
) -> Dict[str, Any]: ) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result) optional_args = super().collect_optional_args(dispatcher, update, check_result)
if isinstance(check_result, dict): if isinstance(check_result, dict):
if self.pass_groups: if self.pass_groups:

View file

@ -17,7 +17,7 @@
# 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/].
"""This module contains the ShippingQueryHandler class.""" """This module contains the ShippingQueryHandler class."""
from typing import Any
from telegram import Update from telegram import Update
from .handler import Handler from .handler import Handler
@ -81,7 +81,7 @@ class ShippingQueryHandler(Handler[Update]):
""" """
def check_update(self, update: Any) -> bool: def check_update(self, update: object) -> bool:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:

View file

@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the StringCommandHandler class.""" """This module contains the StringCommandHandler class."""
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar, Union from typing import TYPE_CHECKING, Callable, Dict, List, Optional, TypeVar, Union
from telegram.utils.helpers import DefaultValue, DEFAULT_FALSE from telegram.utils.helpers import DefaultValue, DEFAULT_FALSE
@ -100,7 +100,7 @@ class StringCommandHandler(Handler[str]):
self.command = command self.command = command
self.pass_args = pass_args self.pass_args = pass_args
def check_update(self, update: Any) -> Optional[List[str]]: def check_update(self, update: object) -> Optional[List[str]]:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:
@ -121,7 +121,7 @@ class StringCommandHandler(Handler[str]):
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
update: str = None, update: str = None,
check_result: Optional[List[str]] = None, check_result: Optional[List[str]] = None,
) -> Dict[str, Any]: ) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result) optional_args = super().collect_optional_args(dispatcher, update, check_result)
if self.pass_args: if self.pass_args:
optional_args['args'] = check_result optional_args['args'] = check_result

View file

@ -19,7 +19,7 @@
"""This module contains the StringRegexHandler class.""" """This module contains the StringRegexHandler class."""
import re import re
from typing import TYPE_CHECKING, Any, Callable, Dict, Match, Optional, Pattern, TypeVar, Union from typing import TYPE_CHECKING, Callable, Dict, Match, Optional, Pattern, TypeVar, Union
from telegram.utils.helpers import DefaultValue, DEFAULT_FALSE from telegram.utils.helpers import DefaultValue, DEFAULT_FALSE
@ -115,7 +115,7 @@ class StringRegexHandler(Handler[str]):
self.pass_groups = pass_groups self.pass_groups = pass_groups
self.pass_groupdict = pass_groupdict self.pass_groupdict = pass_groupdict
def check_update(self, update: Any) -> Optional[Match]: def check_update(self, update: object) -> Optional[Match]:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:
@ -136,7 +136,7 @@ class StringRegexHandler(Handler[str]):
dispatcher: 'Dispatcher', dispatcher: 'Dispatcher',
update: str = None, update: str = None,
check_result: Optional[Match] = None, check_result: Optional[Match] = None,
) -> Dict[str, Any]: ) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result) optional_args = super().collect_optional_args(dispatcher, update, check_result)
if self.pattern: if self.pattern:
if self.pass_groups and check_result: if self.pass_groups and check_result:

View file

@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the TypeHandler class.""" """This module contains the TypeHandler class."""
from typing import TYPE_CHECKING, Any, Callable, Type, TypeVar, Union from typing import TYPE_CHECKING, Callable, Type, TypeVar, Union
from telegram.utils.helpers import DefaultValue, DEFAULT_FALSE from telegram.utils.helpers import DefaultValue, DEFAULT_FALSE
from .handler import Handler from .handler import Handler
@ -93,7 +93,7 @@ class TypeHandler(Handler[UT]):
self.type = type self.type = type
self.strict = strict self.strict = strict
def check_update(self, update: Any) -> bool: def check_update(self, update: object) -> bool:
"""Determines whether an update should be passed to this handlers :attr:`callback`. """Determines whether an update should be passed to this handlers :attr:`callback`.
Args: Args:

View file

@ -219,7 +219,7 @@ class Updater:
self.__lock = Lock() self.__lock = Lock()
self.__threads: List[Thread] = [] self.__threads: List[Thread] = []
def _init_thread(self, target: Callable, name: str, *args: Any, **kwargs: Any) -> None: def _init_thread(self, target: Callable, name: str, *args: object, **kwargs: object) -> None:
thr = Thread( thr = Thread(
target=self._thread_wrapper, target=self._thread_wrapper,
name=f"Bot:{self.bot.id}:{name}", name=f"Bot:{self.bot.id}:{name}",
@ -229,7 +229,7 @@ class Updater:
thr.start() thr.start()
self.__threads.append(thr) self.__threads.append(thr)
def _thread_wrapper(self, target: Callable, *args: Any, **kwargs: Any) -> None: def _thread_wrapper(self, target: Callable, *args: object, **kwargs: object) -> None:
thr_name = current_thread().name thr_name = current_thread().name
self.logger.debug('%s - started', thr_name) self.logger.debug('%s - started', thr_name)
try: try:

View file

@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram VideoNote.""" """This module contains an object that represents a Telegram VideoNote."""
from typing import TYPE_CHECKING, Any, Optional from typing import TYPE_CHECKING, Optional, Any
from telegram import PhotoSize, TelegramObject from telegram import PhotoSize, TelegramObject
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict

View file

@ -77,7 +77,7 @@ class InlineKeyboardMarkup(ReplyMarkup):
return cls(keyboard) return cls(keyboard)
@classmethod @classmethod
def from_button(cls, button: InlineKeyboardButton, **kwargs: Any) -> 'InlineKeyboardMarkup': def from_button(cls, button: InlineKeyboardButton, **kwargs: object) -> 'InlineKeyboardMarkup':
"""Shortcut for:: """Shortcut for::
InlineKeyboardMarkup([[button]], **kwargs) InlineKeyboardMarkup([[button]], **kwargs)
@ -93,7 +93,7 @@ class InlineKeyboardMarkup(ReplyMarkup):
@classmethod @classmethod
def from_row( def from_row(
cls, button_row: List[InlineKeyboardButton], **kwargs: Any cls, button_row: List[InlineKeyboardButton], **kwargs: object
) -> 'InlineKeyboardMarkup': ) -> 'InlineKeyboardMarkup':
"""Shortcut for:: """Shortcut for::
@ -111,7 +111,7 @@ class InlineKeyboardMarkup(ReplyMarkup):
@classmethod @classmethod
def from_column( def from_column(
cls, button_column: List[InlineKeyboardButton], **kwargs: Any cls, button_column: List[InlineKeyboardButton], **kwargs: object
) -> 'InlineKeyboardMarkup': ) -> 'InlineKeyboardMarkup':
"""Shortcut for:: """Shortcut for::

View file

@ -110,7 +110,7 @@ class ReplyKeyboardMarkup(ReplyMarkup):
resize_keyboard: bool = False, resize_keyboard: bool = False,
one_time_keyboard: bool = False, one_time_keyboard: bool = False,
selective: bool = False, selective: bool = False,
**kwargs: Any, **kwargs: object,
) -> 'ReplyKeyboardMarkup': ) -> 'ReplyKeyboardMarkup':
"""Shortcut for:: """Shortcut for::
@ -155,7 +155,7 @@ class ReplyKeyboardMarkup(ReplyMarkup):
resize_keyboard: bool = False, resize_keyboard: bool = False,
one_time_keyboard: bool = False, one_time_keyboard: bool = False,
selective: bool = False, selective: bool = False,
**kwargs: Any, **kwargs: object,
) -> 'ReplyKeyboardMarkup': ) -> 'ReplyKeyboardMarkup':
"""Shortcut for:: """Shortcut for::
@ -201,7 +201,7 @@ class ReplyKeyboardMarkup(ReplyMarkup):
resize_keyboard: bool = False, resize_keyboard: bool = False,
one_time_keyboard: bool = False, one_time_keyboard: bool = False,
selective: bool = False, selective: bool = False,
**kwargs: Any, **kwargs: object,
) -> 'ReplyKeyboardMarkup': ) -> 'ReplyKeyboardMarkup':
"""Shortcut for:: """Shortcut for::

View file

@ -19,7 +19,7 @@
"""This module facilitates the deprecation of functions.""" """This module facilitates the deprecation of functions."""
import warnings import warnings
from typing import Any, Callable, TypeVar from typing import Callable, TypeVar
RT = TypeVar('RT') RT = TypeVar('RT')
@ -42,7 +42,7 @@ def warn_deprecate_obj(old: str, new: str, stacklevel: int = 3) -> None:
def deprecate(func: Callable[..., RT], old: str, new: str) -> Callable[..., RT]: def deprecate(func: Callable[..., RT], old: str, new: str) -> Callable[..., RT]:
"""Warn users invoking old to switch to the new function.""" """Warn users invoking old to switch to the new function."""
def wrapped(*args: Any, **kwargs: Any) -> RT: def wrapped(*args: object, **kwargs: object) -> RT:
warn_deprecate_obj(old, new) warn_deprecate_obj(old, new)
return func(*args, **kwargs) return func(*args, **kwargs)

View file

@ -185,7 +185,7 @@ def to_float_timestamp(
Converts a given time object to a float POSIX timestamp. Converts a given time object to a float POSIX timestamp.
Used to convert different time specifications to a common format. The time object Used to convert different time specifications to a common format. The time object
can be relative (i.e. indicate a time increment, or a time of day) or absolute. can be relative (i.e. indicate a time increment, or a time of day) or absolute.
Any objects from the :class:`datetime` module that are timezone-naive will be assumed object objects from the :class:`datetime` module that are timezone-naive will be assumed
to be in UTC, if ``bot`` is not passed or ``bot.defaults`` is :obj:`None`. to be in UTC, if ``bot`` is not passed or ``bot.defaults`` is :obj:`None`.
Args: Args:
@ -412,7 +412,7 @@ def create_deep_linked_url(bot_username: str, payload: str = None, group: bool =
return f'{base_url}?{key}={payload}' return f'{base_url}?{key}={payload}'
def encode_conversations_to_json(conversations: Dict[str, Dict[Tuple, Any]]) -> str: def encode_conversations_to_json(conversations: Dict[str, Dict[Tuple, object]]) -> str:
"""Helper method to encode a conversations dict (that uses tuples as keys) to a """Helper method to encode a conversations dict (that uses tuples as keys) to a
JSON-serializable way. Use :attr:`_decode_conversations_from_json` to decode. JSON-serializable way. Use :attr:`_decode_conversations_from_json` to decode.
@ -430,7 +430,7 @@ def encode_conversations_to_json(conversations: Dict[str, Dict[Tuple, Any]]) ->
return json.dumps(tmp) return json.dumps(tmp)
def decode_conversations_from_json(json_string: str) -> Dict[str, Dict[Tuple, Any]]: def decode_conversations_from_json(json_string: str) -> Dict[str, Dict[Tuple, object]]:
"""Helper method to decode a conversations dict (that uses tuples as keys) from a """Helper method to decode a conversations dict (that uses tuples as keys) from a
JSON-string created with :attr:`_encode_conversations_to_json`. JSON-string created with :attr:`_encode_conversations_to_json`.
@ -441,7 +441,7 @@ def decode_conversations_from_json(json_string: str) -> Dict[str, Dict[Tuple, An
:obj:`dict`: The conversations dict after decoding :obj:`dict`: The conversations dict after decoding
""" """
tmp = json.loads(json_string) tmp = json.loads(json_string)
conversations: Dict[str, Dict[Tuple, Any]] = {} conversations: Dict[str, Dict[Tuple, object]] = {}
for handler, states in tmp.items(): for handler, states in tmp.items():
conversations[handler] = {} conversations[handler] = {}
for key, state in states.items(): for key, state in states.items():
@ -449,7 +449,7 @@ def decode_conversations_from_json(json_string: str) -> Dict[str, Dict[Tuple, An
return conversations return conversations
def decode_user_chat_data_from_json(data: str) -> DefaultDict[int, Dict[Any, Any]]: def decode_user_chat_data_from_json(data: str) -> DefaultDict[int, Dict[object, object]]:
"""Helper method to decode chat or user data (that uses ints as keys) from a """Helper method to decode chat or user data (that uses ints as keys) from a
JSON-string. JSON-string.
@ -460,7 +460,7 @@ def decode_user_chat_data_from_json(data: str) -> DefaultDict[int, Dict[Any, Any
:obj:`dict`: The user/chat_data defaultdict after decoding :obj:`dict`: The user/chat_data defaultdict after decoding
""" """
tmp: DefaultDict[int, Dict[Any, Any]] = defaultdict(dict) tmp: DefaultDict[int, Dict[object, object]] = defaultdict(dict)
decoded_data = json.loads(data) decoded_data = json.loads(data)
for user, user_data in decoded_data.items(): for user, user_data in decoded_data.items():
user = int(user) user = int(user)
@ -519,7 +519,7 @@ class DefaultValue:
""" """
def __init__(self, value: Any = None): def __init__(self, value: object = None):
self.value = value self.value = value
def __bool__(self) -> bool: def __bool__(self) -> bool:

View file

@ -20,7 +20,7 @@
import logging import logging
from threading import Event from threading import Event
from typing import Callable, List, Optional, Tuple, TypeVar, Union, Any from typing import Callable, List, Optional, Tuple, TypeVar, Union
from telegram.utils.types import JSONDict from telegram.utils.types import JSONDict
@ -60,7 +60,7 @@ class Promise:
pooled_function: Callable[..., RT], pooled_function: Callable[..., RT],
args: Union[List, Tuple], args: Union[List, Tuple],
kwargs: JSONDict, kwargs: JSONDict,
update: Any = None, update: object = None,
error_handling: bool = True, error_handling: bool = True,
): ):
self.pooled_function = pooled_function self.pooled_function = pooled_function
@ -99,7 +99,7 @@ class Promise:
expires. expires.
Raises: Raises:
Any exception raised by :attr:`pooled_function`. object exception raised by :attr:`pooled_function`.
""" """
self.done.wait(timeout=timeout) self.done.wait(timeout=timeout)
if self._exception is not None: if self._exception is not None:

View file

@ -226,7 +226,7 @@ class Request:
return data['result'] return data['result']
def _request_wrapper(self, *args: Any, **kwargs: Any) -> bytes: def _request_wrapper(self, *args: object, **kwargs: Any) -> bytes:
"""Wraps urllib3 request for handling known exceptions. """Wraps urllib3 request for handling known exceptions.
Args: Args:

View file

@ -79,7 +79,7 @@ class WebhookServer:
return return
self.loop.add_callback(self.loop.stop) # type: ignore self.loop.add_callback(self.loop.stop) # type: ignore
def handle_error(self, request: Any, client_address: str) -> None: # pylint: disable=W0613 def handle_error(self, request: object, client_address: str) -> None: # pylint: disable=W0613
"""Handle an error gracefully.""" """Handle an error gracefully."""
self.logger.debug( self.logger.debug(
'Exception happened during processing of request from %s', 'Exception happened during processing of request from %s',

View file

@ -24,7 +24,7 @@ from collections import defaultdict
from queue import Queue from queue import Queue
from threading import Thread, Event from threading import Thread, Event
from time import sleep from time import sleep
from typing import Callable, List, Dict, Any from typing import Callable, List, Dict
import pytest import pytest
import pytz import pytz
@ -407,7 +407,7 @@ def check_shortcut_signature(
def check_shortcut_call( def check_shortcut_call(
kwargs: Dict[str, Any], kwargs: Dict[str, object],
bot_method: Callable, bot_method: Callable,
) -> bool: ) -> bool:
""" """