aiogram/aiogram/utils/deprecated.py

76 lines
2 KiB
Python
Raw Normal View History

2017-08-01 00:40:05 +03:00
"""
Source: https://stackoverflow.com/questions/2536307/decorators-in-the-python-standard-lib-deprecated-specifically
"""
import functools
import inspect
import warnings
def deprecated(reason):
"""
This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
"""
if isinstance(reason, str):
# The @deprecated is used with a 'reason'.
#
# .. code-block:: python
#
# @deprecated("please, use another function")
# def old_function(x, y):
# pass
2017-08-01 00:46:20 +03:00
def decorator(func):
2017-08-01 00:40:05 +03:00
2017-08-01 00:46:20 +03:00
if inspect.isclass(func):
msg = "Call to deprecated class {name} ({reason})."
2017-08-01 00:40:05 +03:00
else:
2017-08-01 00:46:20 +03:00
msg = "Call to deprecated function {name} ({reason})."
@functools.wraps(func)
def wrapper(*args, **kwargs):
warn_deprecated(msg.format(name=func.__name__, reason=reason))
2017-08-01 00:40:05 +03:00
warnings.simplefilter('default', DeprecationWarning)
2017-08-01 00:46:20 +03:00
return func(*args, **kwargs)
2017-08-01 00:40:05 +03:00
2017-08-01 00:46:20 +03:00
return wrapper
2017-08-01 00:40:05 +03:00
return decorator
elif inspect.isclass(reason) or inspect.isfunction(reason):
# The @deprecated is used without any 'reason'.
#
# .. code-block:: python
#
# @deprecated
# def old_function(x, y):
# pass
2017-08-01 00:46:20 +03:00
func1 = reason
2017-08-01 00:40:05 +03:00
2017-08-01 00:46:20 +03:00
if inspect.isclass(func1):
msg1 = "Call to deprecated class {name}."
2017-08-01 00:40:05 +03:00
else:
2017-08-01 00:46:20 +03:00
msg1 = "Call to deprecated function {name}."
2017-08-01 00:40:05 +03:00
2017-08-01 00:46:20 +03:00
@functools.wraps(func1)
def wrapper1(*args, **kwargs):
warn_deprecated(msg1.format(name=func1.__name__))
return func1(*args, **kwargs)
2017-08-01 00:40:05 +03:00
2017-08-01 00:46:20 +03:00
return wrapper1
2017-08-01 00:40:05 +03:00
else:
raise TypeError(repr(type(reason)))
2017-08-01 00:46:20 +03:00
2018-03-30 19:32:23 +03:00
def warn_deprecated(message, warning=DeprecationWarning, stacklevel=2):
2017-08-01 00:46:20 +03:00
warnings.simplefilter('always', warning)
2018-03-30 19:32:23 +03:00
warnings.warn(message, category=warning, stacklevel=stacklevel)
2017-08-01 00:46:20 +03:00
warnings.simplefilter('default', warning)