Skip to content

Commit 484e7fc

Browse files
authored
Merge pull request eternnoir#1214 from SwissCorePy/master
new deprecated decorator
2 parents 983d626 + 791d65e commit 484e7fc

2 files changed

Lines changed: 31 additions & 15 deletions

File tree

‎telebot/util.py‎

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import traceback
77
import warnings
88
import functools
9-
from typing import Any, List, Dict, Union
9+
from typing import Any, Callable, List, Dict, Optional, Union
1010

1111
import queue as Queue
1212
import logging
@@ -420,17 +420,22 @@ def generate_random_token():
420420
return ''.join(random.sample(string.ascii_letters, 16))
421421

422422

423-
def deprecated(func):
424-
"""This is a decorator which can be used to mark functions
425-
as deprecated. It will result in a warning being emitted
426-
when the function is used."""
427-
# https://stackoverflow.com/a/30253848/441814
428-
@functools.wraps(func)
429-
def new_func(*args, **kwargs):
430-
warnings.simplefilter('always', DeprecationWarning) # turn off filter
431-
warnings.warn("Call to deprecated function {}.".format(func.__name__),
432-
category=DeprecationWarning,
433-
stacklevel=2)
434-
warnings.simplefilter('default', DeprecationWarning) # reset filter
435-
return func(*args, **kwargs)
436-
return new_func
423+
def deprecated(warn: bool=False, alternative: Optional[Callable]=None):
424+
"""
425+
Use this decorator to mark functions as deprecated.
426+
When the function is used, an info (or warning if `warn` is True) is logged.
427+
:param warn: If True a warning is logged else an info
428+
:param alternative: The new function to use instead
429+
"""
430+
def decorator(function):
431+
def wrapper(*args, **kwargs):
432+
if not warn:
433+
logger.info(f"`{function.__name__}` is deprecated."
434+
+ (f" Use `{alternative.__name__}` instead" if alternative else ""))
435+
else:
436+
logger.warn(f"`{function.__name__}` is deprecated."
437+
+ (f" Use `{alternative.__name__}` instead" if alternative else ""))
438+
return function(*args, **kwargs)
439+
return wrapper
440+
return decorator
441+

‎tests/test_telebot.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@
1919
CHAT_ID = os.environ['CHAT_ID']
2020
GROUP_ID = os.environ['GROUP_ID']
2121

22+
def _new_test():
23+
pass
24+
25+
@util.deprecated(alternative=_new_test)
26+
def _test():
27+
pass
28+
29+
2230

2331
@pytest.mark.skipif(should_skip, reason="No environment variables configured")
2432
class TestTeleBot:
@@ -615,6 +623,9 @@ def command_handler(message):
615623
tb.process_new_updates([update])
616624
time.sleep(1)
617625
assert update.message.text == 'got' * 2
626+
627+
def test_deprecated_dec(self):
628+
_test()
618629

619630
def test_chat_permissions(self):
620631
return # CHAT_ID is private chat, no permissions can be set

0 commit comments

Comments
 (0)