Skip to content

Instantly share code, notes, and snippets.

@vascokk
Created May 21, 2021 16:45
Show Gist options
  • Save vascokk/e511afb9a57d76d1d9f998818fc8a557 to your computer and use it in GitHub Desktop.
Save vascokk/e511afb9a57d76d1d9f998818fc8a557 to your computer and use it in GitHub Desktop.
"deprecated" decorator in Python
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