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 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
@ -36,15 +36,12 @@ TO = TypeVar('TO', bound='TelegramObject', covariant=True)
class TelegramObject:
"""Base class for most telegram objects."""
# def __init__(self, *args: Any, **_kwargs: Any):
# pass
_id_attrs: Tuple[Any, ...] = ()
_id_attrs: Tuple[object, ...] = ()
def __str__(self) -> str:
return str(self.to_dict())
def __getitem__(self, item: str) -> Any:
def __getitem__(self, item: str) -> object:
return self.__dict__[item]
@staticmethod

View file

@ -27,7 +27,6 @@ from datetime import datetime
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Optional,
@ -110,11 +109,11 @@ RT = TypeVar('RT')
def log(
func: Callable[..., RT], *args: Any, **kwargs: Any # pylint: disable=W0613
func: Callable[..., RT], *args: object, **kwargs: object # pylint: disable=W0613
) -> Callable[..., RT]:
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__)
result = func(*args, **kwargs)
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
defaults = kwargs.get('defaults')

View file

@ -19,7 +19,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Chat."""
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.utils.types import JSONDict, FileInput

View file

@ -20,7 +20,7 @@
import warnings
from abc import ABC, abstractmethod
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
@ -75,7 +75,9 @@ class BasePersistence(ABC):
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)
get_user_data = instance.get_user_data
get_chat_data = instance.get_chat_data
@ -84,13 +86,13 @@ class BasePersistence(ABC):
update_chat_data = instance.update_chat_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())
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())
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())
def update_user_data_replace_bot(user_id: int, data: Dict) -> None:
@ -146,7 +148,7 @@ class BasePersistence(ABC):
return cls._replace_bot(obj, {})
@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)
if obj_id in memo:
return memo[obj_id]
@ -223,7 +225,7 @@ class BasePersistence(ABC):
"""
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)
if obj_id in memo:
return memo[obj_id]
@ -288,7 +290,7 @@ class BasePersistence(ABC):
return obj
@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
persistence object. It should return the ``user_data`` if stored, or an empty
``defaultdict(dict)``.
@ -298,7 +300,7 @@ class BasePersistence(ABC):
"""
@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
persistence object. It should return the ``chat_data`` if stored, or an empty
``defaultdict(dict)``.
@ -308,7 +310,7 @@ class BasePersistence(ABC):
"""
@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
persistence object. It should return the ``bot_data`` if stored, or an empty
:obj:`dict`.

View file

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

View file

@ -21,7 +21,6 @@
import re
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Match,
@ -148,7 +147,7 @@ class CallbackQueryHandler(Handler[Update]):
self.pass_groups = pass_groups
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`.
Args:
@ -173,7 +172,7 @@ class CallbackQueryHandler(Handler[Update]):
dispatcher: 'Dispatcher',
update: Update = None,
check_result: Union[bool, Match] = None,
) -> Dict[str, Any]:
) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result)
if self.pattern:
check_result = cast(Match, check_result)

View file

@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the ChosenInlineResultHandler class."""
from typing import Optional, TypeVar, Union, Any
from typing import Optional, TypeVar, Union
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`.
Args:

View file

@ -19,7 +19,7 @@
"""This module contains the CommandHandler and PrefixHandler classes."""
import re
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.ext import BaseFilter, Filters
@ -177,7 +177,7 @@ class CommandHandler(Handler[Update]):
self.pass_args = pass_args
def check_update(
self, update: Any
self, update: object
) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, Dict]]]]]:
"""Determines whether an update should be passed to this handlers :attr:`callback`.
@ -220,7 +220,7 @@ class CommandHandler(Handler[Update]):
dispatcher: 'Dispatcher',
update: Update = 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)
if self.pass_args and isinstance(check_result, tuple):
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]
def check_update(
self, update: Update
self, update: object
) -> Optional[Union[bool, Tuple[List[str], Optional[Union[bool, Dict]]]]]:
"""Determines whether an update should be passed to this handlers :attr:`callback`.

View file

@ -22,7 +22,7 @@
import logging
import warnings
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.ext import (
@ -286,7 +286,7 @@ class ConversationHandler(Handler[Update]):
return self._entry_points
@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.')
@property
@ -294,7 +294,7 @@ class ConversationHandler(Handler[Update]):
return self._states
@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.')
@property
@ -302,7 +302,7 @@ class ConversationHandler(Handler[Update]):
return self._fallbacks
@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.')
@property
@ -310,7 +310,7 @@ class ConversationHandler(Handler[Update]):
return self._allow_reentry
@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.')
@property
@ -318,7 +318,7 @@ class ConversationHandler(Handler[Update]):
return self._per_user
@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.')
@property
@ -326,7 +326,7 @@ class ConversationHandler(Handler[Update]):
return self._per_chat
@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.')
@property
@ -334,7 +334,7 @@ class ConversationHandler(Handler[Update]):
return self._per_message
@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.')
@property
@ -342,7 +342,7 @@ class ConversationHandler(Handler[Update]):
return self._conversation_timeout
@conversation_timeout.setter
def conversation_timeout(self, value: Any) -> NoReturn:
def conversation_timeout(self, value: object) -> NoReturn:
raise ValueError(
'You can not assign a new value to conversation_timeout after ' 'initialization.'
)
@ -352,7 +352,7 @@ class ConversationHandler(Handler[Update]):
return self._name
@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.')
@property
@ -360,7 +360,7 @@ class ConversationHandler(Handler[Update]):
return self._map_to_parent
@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.')
@property
@ -409,7 +409,7 @@ class ConversationHandler(Handler[Update]):
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
which state the conversation currently is.

View file

@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=R0201, E0401
"""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
@ -100,7 +100,7 @@ class Defaults:
return self._parse_mode
@parse_mode.setter
def parse_mode(self, value: Any) -> NoReturn:
def parse_mode(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to defaults after because it would "
"not have any effect."
@ -111,7 +111,7 @@ class Defaults:
return self._disable_notification
@disable_notification.setter
def disable_notification(self, value: Any) -> NoReturn:
def disable_notification(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to defaults after because it would "
"not have any effect."
@ -122,7 +122,7 @@ class Defaults:
return self._disable_web_page_preview
@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(
"You can not assign a new value to defaults after because it would "
"not have any effect."
@ -133,7 +133,7 @@ class Defaults:
return self._allow_sending_without_reply
@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(
"You can not assign a new value to defaults after because it would "
"not have any effect."
@ -144,7 +144,7 @@ class Defaults:
return self._timeout
@timeout.setter
def timeout(self, value: Any) -> NoReturn:
def timeout(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to defaults after because it would "
"not have any effect."
@ -155,7 +155,7 @@ class Defaults:
return self._quote
@quote.setter
def quote(self, value: Any) -> NoReturn:
def quote(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to defaults after because it would "
"not have any effect."
@ -166,7 +166,7 @@ class Defaults:
return self._tzinfo
@tzinfo.setter
def tzinfo(self, value: Any) -> NoReturn:
def tzinfo(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to defaults after because it would "
"not have any effect."
@ -177,7 +177,7 @@ class Defaults:
return self._run_async
@run_async.setter
def run_async(self, value: Any) -> NoReturn:
def run_async(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to defaults after because it would "
"not have any effect."

View file

@ -19,7 +19,7 @@
"""This module contains the DictPersistence class."""
from copy import deepcopy
from typing import Any, DefaultDict, Dict, Optional, Tuple
from typing import DefaultDict, Dict, Optional, Tuple
from collections import defaultdict
from telegram.utils.helpers import (
@ -169,7 +169,7 @@ class DictPersistence(BasePersistence):
return json.dumps(self.bot_data)
@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."""
return self._conversations
@ -180,7 +180,7 @@ class DictPersistence(BasePersistence):
return self._conversations_json
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
:obj:`defaultdict`.
@ -193,7 +193,7 @@ class DictPersistence(BasePersistence):
self._user_data = defaultdict(dict)
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
:obj:`defaultdict`.
@ -206,7 +206,7 @@ class DictPersistence(BasePersistence):
self._chat_data = defaultdict(dict)
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:

View file

@ -26,7 +26,7 @@ from functools import wraps
from queue import Empty, Queue
from threading import BoundedSemaphore, Event, Lock, Thread, current_thread
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 telegram import TelegramError, Update
@ -45,8 +45,8 @@ DEFAULT_GROUP: int = 0
def run_async(
func: Callable[[Update, CallbackContext], Any]
) -> Callable[[Update, CallbackContext], Any]:
func: Callable[[Update, CallbackContext], object]
) -> Callable[[Update, CallbackContext], object]:
"""
Function decorator that will run the function in a new thread.
@ -64,7 +64,7 @@ def run_async(
"""
@wraps(func)
def async_func(*args: Any, **kwargs: Any) -> Any:
def async_func(*args: object, **kwargs: object) -> object:
warnings.warn(
'The @run_async decorator is deprecated. Use the `run_async` parameter of '
'your Handler or `Dispatcher.run_async` instead.',
@ -162,8 +162,8 @@ class Dispatcher:
stacklevel=3,
)
self.user_data: DefaultDict[int, Dict[Any, Any]] = defaultdict(dict)
self.chat_data: DefaultDict[int, Dict[Any, Any]] = defaultdict(dict)
self.user_data: DefaultDict[int, Dict[object, object]] = defaultdict(dict)
self.chat_data: DefaultDict[int, Dict[object, object]] = defaultdict(dict)
self.bot_data = {}
self.persistence: Optional[BasePersistence] = None
self._update_persistence_lock = Lock()
@ -287,7 +287,7 @@ class Dispatcher:
self.logger.exception('An uncaught error was raised while handling the error.')
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:
"""
Queue a function (with given args/kwargs) to be run asynchronously. Exceptions raised
@ -316,11 +316,11 @@ class Dispatcher:
def _run_async(
self,
func: Callable[..., Any],
*args: Any,
update: Any = None,
func: Callable[..., object],
*args: object,
update: object = None,
error_handling: bool = True,
**kwargs: Any,
**kwargs: object,
) -> Promise:
# TODO: Remove error_handling parameter once we drop the @run_async decorator
promise = Promise(func, args, kwargs, update=update, error_handling=error_handling)
@ -402,7 +402,7 @@ class Dispatcher:
def has_running_threads(self) -> bool:
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.
Note:
@ -530,7 +530,7 @@ class Dispatcher:
del self.handlers[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`.
Args:
@ -540,7 +540,7 @@ class Dispatcher:
with self._update_persistence_lock:
self.__update_persistence(update)
def __update_persistence(self, update: Any = None) -> None:
def __update_persistence(self, update: object = None) -> None:
if self.persistence:
# 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
@ -601,7 +601,7 @@ class Dispatcher:
def add_error_handler(
self,
callback: Callable[[Any, CallbackContext], None],
callback: Callable[[object, CallbackContext], None],
run_async: Union[bool, DefaultValue] = DEFAULT_FALSE, # pylint: disable=W0621
) -> None:
"""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
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.
Args:
@ -647,12 +647,12 @@ class Dispatcher:
self.error_handlers.pop(callback, None)
def dispatch_error(
self, update: Optional[Any], error: Exception, promise: Promise = None
self, update: Optional[object], error: Exception, promise: Promise = None
) -> None:
"""Dispatches an error.
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.
promise (:class:`telegram.utils.Promise`, optional): The promise whose pooled function
raised the error.

View file

@ -107,7 +107,7 @@ class Handler(Generic[UT], ABC):
self.run_async = run_async
@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 handler instance. It should always be overridden.
@ -188,7 +188,7 @@ class Handler(Generic[UT], ABC):
dispatcher: 'Dispatcher',
update: UT = None,
check_result: Any = None, # pylint: disable=W0613
) -> Dict[str, Any]:
) -> Dict[str, object]:
"""
Prepares the optional arguments. If the handler has additional optional args,
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
"""
optional_args: Dict[str, Any] = dict()
optional_args: Dict[str, object] = dict()
if self.pass_update_queue:
optional_args['update_queue'] = dispatcher.update_queue

View file

@ -20,7 +20,6 @@
import re
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Match,
@ -147,7 +146,7 @@ class InlineQueryHandler(Handler[Update]):
self.pass_groups = pass_groups
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`.
@ -174,7 +173,7 @@ class InlineQueryHandler(Handler[Update]):
dispatcher: 'Dispatcher',
update: Update = None,
check_result: Optional[Union[bool, Match]] = None,
) -> Dict[str, Any]:
) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result)
if self.pattern:
check_result = cast(Match, check_result)

View file

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

View file

@ -19,7 +19,7 @@
# TODO: Remove allow_edited
"""This module contains the MessageHandler class."""
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.ext import BaseFilter, Filters
@ -179,7 +179,7 @@ class MessageHandler(Handler[Update]):
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`.
Args:
@ -198,7 +198,7 @@ class MessageHandler(Handler[Update]):
context: 'CallbackContext',
update: Update,
dispatcher: 'Dispatcher',
check_result: Optional[Union[bool, Dict[str, Any]]],
check_result: Optional[Union[bool, Dict[str, object]]],
) -> None:
if isinstance(check_result, dict):
context.update(check_result)

View file

@ -24,7 +24,7 @@ import functools
import queue as q
import threading
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
@ -153,7 +153,7 @@ class DelayQueue(threading.Thread):
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.
Args:
@ -300,7 +300,7 @@ def queuedmessage(method: Callable) -> Callable:
"""
@functools.wraps(method)
def wrapped(self: 'Bot', *args: Any, **kwargs: Any) -> Any:
def wrapped(self: 'Bot', *args: object, **kwargs: object) -> object:
# pylint: disable=W0212
queued = kwargs.pop(
'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.chat_data: Optional[DefaultDict[int, 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:
try:
@ -138,11 +138,11 @@ class PicklePersistence(BasePersistence):
pickle.dump(data, file)
@staticmethod
def dump_file(filename: str, data: Any) -> None:
def dump_file(filename: str, data: object) -> None:
with open(filename, "wb") as 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:
@ -162,7 +162,7 @@ class PicklePersistence(BasePersistence):
self.load_singlefile()
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:
@ -182,7 +182,7 @@ class PicklePersistence(BasePersistence):
self.load_singlefile()
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:

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the PollAnswerHandler class."""
from typing import Any
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`.
Args:

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the PollHandler classes."""
from typing import Any
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`.
Args:

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the PreCheckoutQueryHandler class."""
from typing import Any
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`.
Args:

View file

@ -20,7 +20,7 @@
"""This module contains the RegexHandler class."""
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.ext import Filters, MessageHandler
@ -149,7 +149,7 @@ class RegexHandler(MessageHandler):
dispatcher: 'Dispatcher',
update: Update = 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)
if isinstance(check_result, dict):
if self.pass_groups:

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the ShippingQueryHandler class."""
from typing import Any
from telegram import Update
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`.
Args:

View file

@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""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
@ -100,7 +100,7 @@ class StringCommandHandler(Handler[str]):
self.command = command
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`.
Args:
@ -121,7 +121,7 @@ class StringCommandHandler(Handler[str]):
dispatcher: 'Dispatcher',
update: str = None,
check_result: Optional[List[str]] = None,
) -> Dict[str, Any]:
) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result)
if self.pass_args:
optional_args['args'] = check_result

View file

@ -19,7 +19,7 @@
"""This module contains the StringRegexHandler class."""
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
@ -115,7 +115,7 @@ class StringRegexHandler(Handler[str]):
self.pass_groups = pass_groups
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`.
Args:
@ -136,7 +136,7 @@ class StringRegexHandler(Handler[str]):
dispatcher: 'Dispatcher',
update: str = None,
check_result: Optional[Match] = None,
) -> Dict[str, Any]:
) -> Dict[str, object]:
optional_args = super().collect_optional_args(dispatcher, update, check_result)
if self.pattern:
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/].
"""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 .handler import Handler
@ -93,7 +93,7 @@ class TypeHandler(Handler[UT]):
self.type = type
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`.
Args:

View file

@ -219,7 +219,7 @@ class Updater:
self.__lock = Lock()
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(
target=self._thread_wrapper,
name=f"Bot:{self.bot.id}:{name}",
@ -229,7 +229,7 @@ class Updater:
thr.start()
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
self.logger.debug('%s - started', thr_name)
try:

View file

@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""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.utils.types import JSONDict

View file

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

View file

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

View file

@ -19,7 +19,7 @@
"""This module facilitates the deprecation of functions."""
import warnings
from typing import Any, Callable, TypeVar
from typing import Callable, TypeVar
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]:
"""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)
return func(*args, **kwargs)

View file

@ -185,7 +185,7 @@ def to_float_timestamp(
Converts a given time object to a float POSIX timestamp.
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.
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`.
Args:
@ -412,7 +412,7 @@ def create_deep_linked_url(bot_username: str, payload: str = None, group: bool =
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
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)
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
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
"""
tmp = json.loads(json_string)
conversations: Dict[str, Dict[Tuple, Any]] = {}
conversations: Dict[str, Dict[Tuple, object]] = {}
for handler, states in tmp.items():
conversations[handler] = {}
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
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
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
"""
tmp: DefaultDict[int, Dict[Any, Any]] = defaultdict(dict)
tmp: DefaultDict[int, Dict[object, object]] = defaultdict(dict)
decoded_data = json.loads(data)
for user, user_data in decoded_data.items():
user = int(user)
@ -519,7 +519,7 @@ class DefaultValue:
"""
def __init__(self, value: Any = None):
def __init__(self, value: object = None):
self.value = value
def __bool__(self) -> bool:

View file

@ -20,7 +20,7 @@
import logging
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
@ -60,7 +60,7 @@ class Promise:
pooled_function: Callable[..., RT],
args: Union[List, Tuple],
kwargs: JSONDict,
update: Any = None,
update: object = None,
error_handling: bool = True,
):
self.pooled_function = pooled_function
@ -99,7 +99,7 @@ class Promise:
expires.
Raises:
Any exception raised by :attr:`pooled_function`.
object exception raised by :attr:`pooled_function`.
"""
self.done.wait(timeout=timeout)
if self._exception is not None:

View file

@ -226,7 +226,7 @@ class Request:
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.
Args:

View file

@ -79,7 +79,7 @@ class WebhookServer:
return
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."""
self.logger.debug(
'Exception happened during processing of request from %s',

View file

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