Created
May 21, 2021 16:45
-
-
Save vascokk/e511afb9a57d76d1d9f998818fc8a557 to your computer and use it in GitHub Desktop.
"deprecated" decorator in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import warnings | |
import functools | |
def deprecated(_func=None, *, replaced_with=None): | |
"""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.""" | |
def decorator_deprecated(func): | |
@functools.wraps(func) | |
def wrapper_decorator(*args, **kwargs): | |
warnings.simplefilter('always', DeprecationWarning) # turn off filter | |
if replaced_with: | |
msg = "Call to deprecated function {}. Raplaced with: {}".format(func.__name__, replaced_with) | |
else: | |
msg = "Call to deprecated function {}.".format(func.__name__) | |
warnings.warn(msg, | |
category=DeprecationWarning, | |
stacklevel=2) | |
warnings.simplefilter('default', DeprecationWarning) # reset filter | |
return func(*args, **kwargs) | |
return wrapper_decorator | |
if _func is None: | |
return decorator_deprecated | |
else: | |
return decorator_deprecated(_func) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment