Skip to content

Commit cf14239

Browse files
harshil21Bibo-Joshi
authored andcommitted
Warnings Overhaul (python-telegram-bot#2662)
1 parent e953830 commit cf14239

16 files changed

+207
-124
lines changed

docs/source/telegram.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,3 +182,4 @@ utils
182182
telegram.utils.promise
183183
telegram.utils.request
184184
telegram.utils.types
185+
telegram.utils.warnings
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/utils/warnings.py
2+
3+
telegram.utils.warnings Module
4+
===============================
5+
6+
.. automodule:: telegram.utils.warnings
7+
:members:
8+
:show-inheritance:

telegram/base.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@
2222
except ImportError:
2323
import json # type: ignore[no-redef]
2424

25-
import warnings
2625
from typing import TYPE_CHECKING, List, Optional, Type, TypeVar, Tuple
2726

2827
from telegram.utils.types import JSONDict
28+
from telegram.utils.warnings import warn
2929

3030
if TYPE_CHECKING:
3131
from telegram import Bot
@@ -140,14 +140,16 @@ def __eq__(self, other: object) -> bool:
140140
# pylint: disable=no-member
141141
if isinstance(other, self.__class__):
142142
if self._id_attrs == ():
143-
warnings.warn(
143+
warn(
144144
f"Objects of type {self.__class__.__name__} can not be meaningfully tested for"
145-
" equivalence."
145+
" equivalence.",
146+
stacklevel=2,
146147
)
147148
if other._id_attrs == ():
148-
warnings.warn(
149+
warn(
149150
f"Objects of type {other.__class__.__name__} can not be meaningfully tested"
150-
" for equivalence."
151+
" for equivalence.",
152+
stacklevel=2,
151153
)
152154
return self._id_attrs == other._id_attrs
153155
return super().__eq__(other)

telegram/bot.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121

2222
import functools
2323
import logging
24-
import warnings
2524
from datetime import datetime
2625

2726
from typing import (
@@ -91,7 +90,7 @@
9190
)
9291
from telegram.constants import MAX_INLINE_QUERY_RESULTS
9392
from telegram.error import InvalidToken, TelegramError
94-
from telegram.utils.deprecate import TelegramDeprecationWarning
93+
from telegram.utils.warnings import PTBDeprecationWarning, warn
9594
from telegram.utils.helpers import (
9695
DEFAULT_NONE,
9796
DefaultValue,
@@ -198,10 +197,10 @@ def __init__(
198197
self.defaults = defaults
199198

200199
if self.defaults:
201-
warnings.warn(
200+
warn(
202201
'Passing Defaults to telegram.Bot is deprecated. Use telegram.ext.ExtBot instead.',
203-
TelegramDeprecationWarning,
204-
stacklevel=3,
202+
PTBDeprecationWarning,
203+
stacklevel=4,
205204
)
206205

207206
if base_url is None:

telegram/ext/basepersistence.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
# You should have received a copy of the GNU Lesser Public License
1818
# along with this program. If not, see [http://www.gnu.org/licenses/].
1919
"""This module contains the BasePersistence class."""
20-
import warnings
2120
from abc import ABC, abstractmethod
2221
from copy import copy
2322
from typing import Dict, Optional, Tuple, cast, ClassVar, Generic, DefaultDict, NamedTuple
@@ -26,6 +25,7 @@
2625
import telegram.ext.extbot
2726

2827
from telegram.ext.utils.types import UD, CD, BD, ConversationDict, CDCData
28+
from telegram.utils.warnings import warn, PTBRuntimeWarning
2929

3030

3131
class PersistenceInput(NamedTuple):
@@ -230,21 +230,21 @@ def _replace_bot(cls, obj: object, memo: Dict[int, object]) -> object: # pylint
230230
return new_immutable
231231
if isinstance(obj, type):
232232
# classes usually do have a __dict__, but it's not writable
233-
warnings.warn(
234-
'BasePersistence.replace_bot does not handle classes. See '
235-
'the docs of BasePersistence.replace_bot for more information.',
236-
RuntimeWarning,
233+
warn(
234+
f'BasePersistence.replace_bot does not handle classes such as {obj.__name__!r}. '
235+
'See the docs of BasePersistence.replace_bot for more information.',
236+
PTBRuntimeWarning,
237237
)
238238
return obj
239239

240240
try:
241241
new_obj = copy(obj)
242242
memo[obj_id] = new_obj
243243
except Exception:
244-
warnings.warn(
244+
warn(
245245
'BasePersistence.replace_bot does not handle objects that can not be copied. See '
246246
'the docs of BasePersistence.replace_bot for more information.',
247-
RuntimeWarning,
247+
PTBRuntimeWarning,
248248
)
249249
memo[obj_id] = obj
250250
return obj
@@ -282,10 +282,10 @@ def _replace_bot(cls, obj: object, memo: Dict[int, object]) -> object: # pylint
282282
memo[obj_id] = new_obj
283283
return new_obj
284284
except Exception as exception:
285-
warnings.warn(
285+
warn(
286286
f'Parsing of an object failed with the following exception: {exception}. '
287287
f'See the docs of BasePersistence.replace_bot for more information.',
288-
RuntimeWarning,
288+
PTBRuntimeWarning,
289289
)
290290

291291
memo[obj_id] = obj
@@ -333,20 +333,20 @@ def _insert_bot(self, obj: object, memo: Dict[int, object]) -> object: # pylint
333333
return new_immutable
334334
if isinstance(obj, type):
335335
# classes usually do have a __dict__, but it's not writable
336-
warnings.warn(
337-
'BasePersistence.insert_bot does not handle classes. See '
338-
'the docs of BasePersistence.insert_bot for more information.',
339-
RuntimeWarning,
336+
warn(
337+
f'BasePersistence.insert_bot does not handle classes such as {obj.__name__!r}. '
338+
'See the docs of BasePersistence.insert_bot for more information.',
339+
PTBRuntimeWarning,
340340
)
341341
return obj
342342

343343
try:
344344
new_obj = copy(obj)
345345
except Exception:
346-
warnings.warn(
346+
warn(
347347
'BasePersistence.insert_bot does not handle objects that can not be copied. See '
348348
'the docs of BasePersistence.insert_bot for more information.',
349-
RuntimeWarning,
349+
PTBRuntimeWarning,
350350
)
351351
memo[obj_id] = obj
352352
return obj
@@ -384,10 +384,10 @@ def _insert_bot(self, obj: object, memo: Dict[int, object]) -> object: # pylint
384384
memo[obj_id] = new_obj
385385
return new_obj
386386
except Exception as exception:
387-
warnings.warn(
387+
warn(
388388
f'Parsing of an object failed with the following exception: {exception}. '
389389
f'See the docs of BasePersistence.insert_bot for more information.',
390-
RuntimeWarning,
390+
PTBRuntimeWarning,
391391
)
392392

393393
memo[obj_id] = obj

telegram/ext/conversationhandler.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
"""This module contains the ConversationHandler."""
2121

2222
import logging
23-
import warnings
2423
import functools
2524
import datetime
2625
from threading import Lock
@@ -39,6 +38,7 @@
3938
from telegram.ext.utils.promise import Promise
4039
from telegram.ext.utils.types import ConversationDict
4140
from telegram.ext.utils.types import CCT
41+
from telegram.utils.warnings import warn
4242

4343
if TYPE_CHECKING:
4444
from telegram.ext import Dispatcher, Job
@@ -259,9 +259,10 @@ def __init__(
259259
raise ValueError("'per_user', 'per_chat' and 'per_message' can't all be 'False'")
260260

261261
if self.per_message and not self.per_chat:
262-
warnings.warn(
262+
warn(
263263
"If 'per_message=True' is used, 'per_chat=True' should also be used, "
264-
"since message IDs are not globally unique."
264+
"since message IDs are not globally unique.",
265+
stacklevel=2,
265266
)
266267

267268
all_handlers: List[Handler] = []
@@ -274,37 +275,41 @@ def __init__(
274275
if self.per_message:
275276
for handler in all_handlers:
276277
if not isinstance(handler, CallbackQueryHandler):
277-
warnings.warn(
278-
"If 'per_message=True', all entry points and state handlers"
278+
warn(
279+
"If 'per_message=True', all entry points, state handlers, and fallbacks"
279280
" must be 'CallbackQueryHandler', since no other handlers "
280-
"have a message context."
281+
"have a message context.",
282+
stacklevel=2,
281283
)
282284
break
283285
else:
284286
for handler in all_handlers:
285287
if isinstance(handler, CallbackQueryHandler):
286-
warnings.warn(
288+
warn(
287289
"If 'per_message=False', 'CallbackQueryHandler' will not be "
288-
"tracked for every message."
290+
"tracked for every message.",
291+
stacklevel=2,
289292
)
290293
break
291294

292295
if self.per_chat:
293296
for handler in all_handlers:
294297
if isinstance(handler, (InlineQueryHandler, ChosenInlineResultHandler)):
295-
warnings.warn(
298+
warn(
296299
"If 'per_chat=True', 'InlineQueryHandler' can not be used, "
297-
"since inline queries have no chat context."
300+
"since inline queries have no chat context.",
301+
stacklevel=2,
298302
)
299303
break
300304

301305
if self.conversation_timeout:
302306
for handler in all_handlers:
303307
if isinstance(handler, self.__class__):
304-
warnings.warn(
308+
warn(
305309
"Using `conversation_timeout` with nested conversations is currently not "
306310
"supported. You can still try to use it, but it will likely behave "
307-
"differently from what you expect."
311+
"differently from what you expect.",
312+
stacklevel=2,
308313
)
309314
break
310315

@@ -644,8 +649,8 @@ def handle_update( # type: ignore[override]
644649
new_state, dispatcher, update, context, conversation_key
645650
)
646651
else:
647-
self.logger.warning(
648-
"Ignoring `conversation_timeout` because the Dispatcher has no JobQueue."
652+
warn(
653+
"Ignoring `conversation_timeout` because the Dispatcher has no JobQueue.",
649654
)
650655

651656
if isinstance(self.map_to_parent, dict) and new_state in self.map_to_parent:
@@ -680,9 +685,9 @@ def _update_state(self, new_state: object, key: Tuple[int, ...]) -> None:
680685

681686
elif new_state is not None:
682687
if new_state not in self.states:
683-
warnings.warn(
688+
warn(
684689
f"Handler returned state {new_state} which is unknown to the "
685-
f"ConversationHandler{' ' + self.name if self.name is not None else ''}."
690+
f"ConversationHandler{' ' + self.name if self.name is not None else ''}.",
686691
)
687692
with self._conversations_lock:
688693
self.conversations[key] = new_state
@@ -711,9 +716,9 @@ def _trigger_timeout(self, context: CallbackContext) -> None:
711716
try:
712717
handler.handle_update(ctxt.update, ctxt.dispatcher, check, callback_context)
713718
except DispatcherHandlerStop:
714-
self.logger.warning(
719+
warn(
715720
'DispatcherHandlerStop in TIMEOUT state of '
716-
'ConversationHandler has no effect. Ignoring.'
721+
'ConversationHandler has no effect. Ignoring.',
717722
)
718723

719724
self._update_state(self.END, ctxt.conversation_key)

telegram/ext/dispatcher.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
"""This module contains the Dispatcher class."""
2020

2121
import logging
22-
import warnings
2322
import weakref
2423
from collections import defaultdict
2524
from queue import Empty, Queue
@@ -47,6 +46,7 @@
4746
import telegram.ext.extbot
4847
from telegram.ext.callbackdatacache import CallbackDataCache
4948
from telegram.ext.utils.promise import Promise
49+
from telegram.utils.warnings import warn
5050
from telegram.utils.helpers import DefaultValue, DEFAULT_FALSE
5151
from telegram.ext.utils.types import CCT, UD, CD, BD
5252

@@ -199,8 +199,9 @@ def __init__(
199199
self.context_types = cast(ContextTypes[CCT, UD, CD, BD], context_types or ContextTypes())
200200

201201
if self.workers < 1:
202-
warnings.warn(
203-
'Asynchronous callbacks can not be processed without at least one worker thread.'
202+
warn(
203+
'Asynchronous callbacks can not be processed without at least one worker thread.',
204+
stacklevel=2,
204205
)
205206

206207
self.user_data: DefaultDict[int, UD] = defaultdict(self.context_types.user_data)
@@ -315,9 +316,9 @@ def _pooled(self) -> None:
315316
continue
316317

317318
if isinstance(promise.exception, DispatcherHandlerStop):
318-
self.logger.warning(
319-
'DispatcherHandlerStop is not supported with async functions; func: %s',
320-
promise.pooled_function.__name__,
319+
warn(
320+
'DispatcherHandlerStop is not supported with async functions; '
321+
f'func: {promise.pooled_function.__name__}',
321322
)
322323
continue
323324

telegram/ext/updater.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020

2121
import logging
2222
import ssl
23-
import warnings
2423
from queue import Queue
2524
from signal import SIGABRT, SIGINT, SIGTERM, signal
2625
from threading import Event, Lock, Thread, current_thread
@@ -42,7 +41,7 @@
4241
from telegram import Bot, TelegramError
4342
from telegram.error import InvalidToken, RetryAfter, TimedOut, Unauthorized
4443
from telegram.ext import Dispatcher, JobQueue, ContextTypes, ExtBot
45-
from telegram.utils.deprecate import TelegramDeprecationWarning
44+
from telegram.utils.warnings import PTBDeprecationWarning, warn
4645
from telegram.utils.helpers import get_signal_name, DEFAULT_FALSE, DefaultValue
4746
from telegram.utils.request import Request
4847
from telegram.ext.utils.types import CCT, UD, CD, BD
@@ -211,14 +210,14 @@ def __init__( # type: ignore[no-untyped-def,misc]
211210
):
212211

213212
if defaults and bot:
214-
warnings.warn(
213+
warn(
215214
'Passing defaults to an Updater has no effect when a Bot is passed '
216215
'as well. Pass them to the Bot instead.',
217-
TelegramDeprecationWarning,
216+
PTBDeprecationWarning,
218217
stacklevel=2,
219218
)
220219
if arbitrary_callback_data is not DEFAULT_FALSE and bot:
221-
warnings.warn(
220+
warn(
222221
'Passing arbitrary_callback_data to an Updater has no '
223222
'effect when a Bot is passed as well. Pass them to the Bot instead.',
224223
stacklevel=2,
@@ -250,9 +249,10 @@ def __init__( # type: ignore[no-untyped-def,misc]
250249
if bot is not None:
251250
self.bot = bot
252251
if bot.request.con_pool_size < con_pool_size:
253-
self.logger.warning(
254-
'Connection pool of Request object is smaller than optimal value (%s)',
255-
con_pool_size,
252+
warn(
253+
f'Connection pool of Request object is smaller than optimal value '
254+
f'{con_pool_size}',
255+
stacklevel=2,
256256
)
257257
else:
258258
# we need a connection pool the size of:
@@ -299,9 +299,10 @@ def __init__( # type: ignore[no-untyped-def,misc]
299299

300300
self.bot = dispatcher.bot
301301
if self.bot.request.con_pool_size < con_pool_size:
302-
self.logger.warning(
303-
'Connection pool of Request object is smaller than optimal value (%s)',
304-
con_pool_size,
302+
warn(
303+
f'Connection pool of Request object is smaller than optimal value '
304+
f'{con_pool_size}',
305+
stacklevel=2,
305306
)
306307
self.update_queue = dispatcher.update_queue
307308
self.__exception_event = dispatcher.exception_event

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy