8000 Improve Warning Categories & Stacklevels (#3674) · Devors/python-telegram-bot@3f444da · GitHub 8000
[go: up one dir, main page]

Skip to content

Commit 3f444da

Browse files
authored
Improve Warning Categories & Stacklevels (python-telegram-bot#3674)
1 parent f23315d commit 3f444da

28 files changed

+309
-106
lines changed

telegram/_bot.py

Lines changed: 38 additions & 12 deletions
10000
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ def __init__(
273273
warning_string = "request"
274274

275275
if warning_string:
276-
warn(
276+
self._warn(
277277
f"You set the HTTP version for the {warning_string} HTTPXRequest instance to "
278278
f"HTTP/2. The self hosted bot api instances only support HTTP/1.1. You should "
279279
f"either run a HTTP proxy in front of it which supports HTTP/2 or use HTTP/1.1.",
@@ -338,6 +338,15 @@ def private_key(self) -> Optional[Any]:
338338
"""
339339
return self._private_key
340340

341+
@classmethod
342+
def _warn(
343+
cls, message: str, category: Type[Warning] = PTBUserWarning, stacklevel: int = 0
344+
) -> None:
345+
"""Convenience method to issue a warning. This method is here mostly to make it easier
346+
for ExtBot to add 1 level to all warning calls.
347+
"""
348+
warn(message=message, category=category, stacklevel=stacklevel + 1)
349+
341350
def __reduce__(self) -> NoReturn:
342351
"""Customizes how :func:`copy.deepcopy` processes objects of this type. Bots can not
343352
be pickled and this method will always raise an exception.
@@ -1157,7 +1166,10 @@ async def send_audio(
11571166
11581167
"""
11591168
thumbnail_or_thumb: FileInput = warn_about_thumb_return_thumbnail(
1160-
deprecated_arg=thumb, new_arg=thumbnail
1169+
deprecated_arg=thumb,
1170+
new_arg=thumbnail,
1171+
warn_callback=self._warn,
1172+
stacklevel=3,
11611173
)
11621174
data: JSONDict = {
11631175
"chat_id": chat_id,
@@ -1294,7 +1306,10 @@ async def send_document(
12941306
12951307
"""
12961308
thumbnail_or_thumb: FileInput = warn_about_thumb_return_thumbnail(
1297-
deprecated_arg=thumb, new_arg=thumbnail
1309+
deprecated_arg=thumb,
1310+
new_arg=thumbnail,
1311+
warn_callback=self._warn,
1312+
stacklevel=3,
12981313
)
12991314

13001315
data: JSONDict = {
@@ -1531,7 +1546,10 @@ async def send_video(
15311546
15321547
"""
15331548
thumbnail_or_thumb: FileInput = warn_about_thumb_return_thumbnail(
1534-
deprecated_arg=thumb, new_arg=thumbnail
1549+
deprecated_arg=thumb,
1550+
new_arg=thumbnail,
1551+
warn_callback=self._warn,
1552+
stacklevel=3,
15351553
)
15361554
data: JSONDict = {
15371555
"chat_id": chat_id,
@@ -1664,7 +1682,10 @@ async def send_video_note(
16641682
16651683
"""
16661684
thumbnail_or_thumb: FileInput = warn_about_thumb_return_thumbnail(
1667-
deprecated_arg=thumb, new_arg=thumbnail
1685+
deprecated_arg=thumb,
1686+
new_arg=thumbnail,
1687+
warn_callback=self._warn,
1688+
stacklevel=3,
16681689
)
16691690
data: JSONDict = {
16701691
"chat_id": chat_id,
@@ -1807,6 +1828,8 @@ async def send_animation(
18071828
thumbnail_or_thumb: FileInput = warn_about_thumb_return_thumbnail(
18081829
deprecated_arg=thumb,
18091830
new_arg=thumbnail,
1831+
warn_callback=self._warn,
1832+
stacklevel=3,
18101833
)
18111834
data: JSONDict = {
18121835
"chat_id": chat_id,
@@ -5614,11 +5637,12 @@ async def upload_sticker_file(
56145637
# only, which would have been confusing.
56155638

56165639
if png_sticker:
5617-
warn(
5640+
self._warn(
56185641
"Since Bot API 6.6, the parameter `png_sticker` for "
56195642
"`upload_sticker_file` is deprecated. Please use the new parameters "
56205643
"`sticker` and `sticker_format` instead.",
5621-
stacklevel=4,
5644+
stacklevel=3,
5645+
category=PTBDeprecationWarning,
56225646
)
56235647

56245648
data: JSONDict = {
@@ -5813,11 +5837,12 @@ async def create_new_sticker_set(
58135837
# only, which would have been confusing.
58145838

58155839
if any(pre_api_6_6_params.values()):
5816-
warn(
5840+
self._warn(
58175841
f"Since Bot API 6.6, the parameters {set(pre_api_6_6_params)} for "
58185842
"`create_new_sticker_set` are deprecated. Please use the new parameter "
58195843
"`stickers` and `sticker_format` instead.",
5820-
stacklevel=4,
5844+
stacklevel=3,
5845+
category=PTBDeprecationWarning,
58215846
)
58225847

58235848
data: JSONDict = {
@@ -5984,11 +6009,12 @@ async def add_sticker_to_set(
59846009
)
59856010

59866011
if any(pre_api_6_6_params.values()):
5987-
warn(
6012+
self._warn(
59886013
f"Since Bot API 6.6, the parameters {set(pre_api_6_6_params)} for "
59896014
"`add_sticker_to_set` are deprecated. Please use the new parameter `sticker` "
59906015
"instead.",
5991-
stacklevel=4,
6016+
stacklevel=3,
6017+
category=PTBDeprecationWarning,
59926018
)
59936019

59946020
data: JSONDict = {
@@ -6224,7 +6250,7 @@ async def set_sticker_set_thumb(
62246250
:class:`telegram.error.TelegramError`
62256251
62266252
"""
6227-
warn(
6253+
self._warn(
62286254
message=(
62296255
"Bot API 6.6 renamed the method 'setStickerSetThumb' to 'setStickerSetThumbnail', "
62306256
"hence method 'set_sticker_set_thumb' was renamed to 'set_sticker_set_thumbnail' "

telegram/_files/_basethumbedmedium.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def __init__(
9393
deprecated_arg_name="thumb",
9494
new_arg_name="thumbnail",
9595
bot_api_version="6.6",
96-
stacklevel=4,
96+
stacklevel=3,
9797
)
9898

9999
@property

telegram/_utils/warnings_transition.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@
2323
2424
.. versionadded:: 20.2
2525
"""
26-
import functools
27-
from typing import Any
26+
from typing import Any, Callable, Type
2827

2928
from telegram._utils.warnings import warn
3029
from telegram.warnings import PTBDeprecationWarning
@@ -38,7 +37,8 @@ def warn_about_deprecated_arg_return_new_arg(
3837
deprecated_arg_name: str,
3938
new_arg_name: str,
4039
bot_api_version: str,
41-
stacklevel: int = 3,
40+
stacklevel: int = 2,
41+
warn_callback: Callable[[str, Type[Warning], int], None] = warn,
4242
) -> Any:
4343
"""A helper function for the transition in API when argument is renamed.
4444
@@ -58,11 +58,11 @@ def warn_about_deprecated_arg_return_new_arg(
5858
)
5959

6060
if deprecated_arg:
61-
warn(
61+
warn_callback(
6262
f"Bot API {bot_api_version} renamed the argument '{deprecated_arg_name}' to "
6363
f"'{new_arg_name}'.",
6464
PTBDeprecationWarning,
65-
stacklevel=stacklevel,
65+
stacklevel + 1,
6666
)
6767
return deprecated_arg
6868

@@ -73,7 +73,7 @@ def warn_about_deprecated_attr_in_property(
7373
deprecated_attr_name: str,
7474
new_attr_name: str,
7575
bot_api_version: str,
76-
stacklevel: int = 3,
76+
stacklevel: int = 2,
7777
) -> None:
7878
"""A helper function for the transition in API when attribute is renamed. Call from properties.
7979
@@ -83,16 +83,25 @@ def warn_about_deprecated_attr_in_property(
8383
f"Bot API {bot_api_version} renamed the attribute '{deprecated_attr_name}' to "
8484
f"'{new_attr_name}'.",
8585
PTBDeprecationWarning,
86-
stacklevel=stacklevel,
86+
stacklevel=stacklevel + 1,
8787
)
8888

8989

90-
warn_about_thumb_return_thumbnail = functools.partial(
91-
warn_about_deprecated_arg_return_new_arg,
92-
deprecated_arg_name="thumb",
93-
new_arg_name="thumbnail",
94-
bot_api_version="6.6",
95-
)
96-
"""A helper function to warn about using a deprecated 'thumb' argument and return it or the new
97-
'thumbnail' argument, introduced in API 6.6.
98-
"""
90+
def warn_about_thumb_return_thumbnail(
91+
deprecated_arg: Any,
92+
new_arg: Any,
93+
stacklevel: int = 2,
94+
warn_callback: Callable[[str, Type[Warning], int], None] = warn,
95+
) -> Any:
96+
"""A helper function to warn about using a deprecated 'thumb' argument and return it or the
97+
new 'thumbnail' argument, introduced in API 6.6.
98+
"""
99+
return warn_about_deprecated_arg_return_new_arg(
100+
deprecated_arg=deprecated_arg,
101+
new_arg=new_arg,
102+
warn_callback=warn_callback,
103+
deprecated_arg_name="thumb",
104+
new_arg_name="thumbnail",
105+
bot_api_version="6.6",
106+
stacklevel=stacklevel + 1,
107+
)

telegram/ext/_conversationhandler.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -840,11 +840,13 @@ async def handle_update( # type: ignore[override]
840840
if application.job_queue is None:
841841
warn(
842842
"Ignoring `conversation_timeout` because the Application has no JobQueue.",
843+
stacklevel=1,
843844
)
844845
elif not application.job_queue.scheduler.running:
845846
warn(
846847
"Ignoring `conversation_timeout` because the Applications JobQueue is "
847848
"not running.",
849+
stacklevel=1,
848850
)
849851
elif isinstance(new_state, asyncio.Task):
850852
# Add the new timeout job
@@ -931,6 +933,7 @@ async def _trigger_timeout(self, context: CCT) -> None:
931933
warn(
932934
"ApplicationHandlerStop in TIMEOUT state of "
933935
"ConversationHandler has no effect. Ignoring.",
936+
stacklevel=2,
934937
)
935938

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

telegram/ext/_extbot.py

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
# You should have received a copy of the GNU Lesser Public License
1919
# along with this program. If not, see [http://www.gnu.org/licenses/].
2020
"""This module contains an object that represents a Telegram Bot with convenience extensions."""
21-
import warnings
2221
from copy import copy
2322
from datetime import datetime
2423
from typing import (
@@ -31,6 +30,7 @@
3130
Optional,
3231
Sequence,
3332
Tuple,
33+
Type,
3434
TypeVar,
3535
Union,
3636
cast,
@@ -87,11 +87,10 @@
8787
from telegram._utils.defaultvalue import DEFAULT_NONE, DefaultValue
8888
from telegram._utils.logging import get_logger
8989
from telegram._utils.types import DVInput, FileInput, JSONDict, ODVInput, ReplyMarkup
90-
from telegram._utils.warnings import warn
9190
from telegram.ext._callbackdatacache import CallbackDataCache
9291
from telegram.ext._utils.types import RLARGS
9392
from telegram.request import BaseRequest
94-
from telegram.warnings import PTBDeprecationWarning
93+
from telegram.warnings import PTBUserWarning
9594

9695
if TYPE_CHECKING:
9796
from telegram import (
@@ -235,6 +234,15 @@ def __init__(
235234

236235
self._callback_data_cache = CallbackDataCache(bot=self, maxsize=maxsize)
237236

237+
@classmethod
238+
def _warn(
239+
cls, message: str, category: Type[Warning] = PTBUserWarning, stacklevel: int = 0
240+
) -> None:
241+
"""We override this method to add one more level to the stacklevel, so that the warning
242+
points to the user's code, not to the PTB code.
243+
"""
244+
super()._warn(message=message, category=category, stacklevel=stacklevel + 2)
245+
238246
@property
239247
def callback_data_cache(self) -> Optional[CallbackDataCache]:
240248
""":class:`telegram.ext.CallbackDataCache`: Optional. The cache for
@@ -3284,30 +3292,16 @@ async def set_sticker_set_thumb(
32843292
api_kwargs: JSONDict = None,
32853293
rate_limit_args: RLARGS = None,
32863294
) -> bool:
3287-
# Manually issue deprecation here to get the stacklevel right
3288-
# Suppress the warning issued by super().set_sticker_set_thumb just in case
3289-
# the user explicitly enables deprecation warnings
3290-
# Unfortunately this is not entirely reliable (see tests), but it's a best effort solution
3291-
warn(
3292-
message=(
3293-
"Bot API 6.6 renamed the method 'setStickerSetThumb' to 'setStickerSetThumbnail', "
3294-
"hence method 'set_sticker_set_thumb' was renamed to 'set_sticker_set_thumbnail' "
3295-
"in PTB."
3296-
),
3297-
category=PTBDeprecationWarning,
3298-
stacklevel=2,
3299-
)
3300-
with warnings.catch_warnings():
3301-
return await super().set_sticker_set_thumb(
3302-
name=name,
3303-
user_id=user_id,
3304-
thumb=thumb,
3305-
read_timeout=read_timeout,
3306-
write_timeout=write_timeout,
3307-
connect_timeout=connect_timeout,
3308-
pool_timeout=pool_timeout,
3309-
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
3310-
)
3295+
return await super().set_sticker_set_thumb(
3296+
name=name,
3297+
user_id=user_id,
3298+
thumb=thumb,
3299+
read_timeout=read_timeout,
3300+
write_timeout=write_timeout,
3301+
connect_timeout=connect_timeout,
3302+
pool_timeout=pool_timeout,
3303+
api_kwargs=self._merge_api_rl_kwargs(api_kwargs, rate_limit_args),
3304+
)
33113305

33123306
async def set_webhook(
33133307
self,

telegram/ext/_picklepersistence.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@ def persistent_id(self, obj: object) -> Optional[str]:
9898
if obj is self._bot:
9999
return _REPLACED_KNOWN_BOT
100100
if isinstance(obj, Bot):
101-
warn("Unknown bot instance found. Will be replaced by `None` during unpickling")
101+
warn(
102+
"Unknown bot instance found. Will be replaced by `None` during unpickling",
103+
stacklevel=2,
104+
)
102105
return _REPLACED_UNKNOWN_BOT
103106
return None # pickles as usual
104107

tests/_files/test_animation.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@
3131
check_shortcut_call,
3232
check_shortcut_signature,
3333
)
34-
from tests.auxil.deprecations import check_thumb_deprecation_warnings_for_args_and_attrs
34+
from tests.auxil.deprecations import (
35+
check_thumb_deprecation_warning_for_method_args,
36+
check_thumb_deprecation_warnings_for_args_and_attrs,
37+
)
3538
from tests.auxil.files import data_file
3639
from tests.auxil.slots import mro_slots
3740

@@ -191,6 +194,19 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs):
191194
monkeypatch.setattr(bot.request, "post", make_assertion)
192195
assert await bot.send_animation(animation=animation, chat_id=chat_id)
193196

197+
@pytest.mark.parametrize("bot_class", ["Bot", "ExtBot"])
198+
async def test_send_animation_thumb_deprecation_warning(
199+
self, recwarn, monkeypatch, bot_class, bot, raw_bot, chat_id, animation
200+
):
201+
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
202+
return True
203+
204+
bot = raw_bot if bot_class == "Bot" else bot
205+
206+
monkeypatch.setattr(bot.request, "post", make_assertion)
207+
await bot.send_animation(chat_id, animation, thumb="thumb")
208+
check_thumb_deprecation_warning_for_method_args(recwarn, __file__)
209+
194210
async def test_send_animation_with_local_files_throws_error_with_different_thumb_and_thumbnail(
195211
self, bot, chat_id
196212
):

0 commit comments

Comments
 (0)
0