Created
December 31, 2013 20:49
-
-
Save kgriffs/8202106 to your computer and use it in GitHub Desktop.
Deprecated decorator for Python. Uses clever introspection to set a helpful filename and lineno in the warning message.
This file contains 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 functools | |
import inspect | |
import warnings | |
# NOTE(kgriffs): We don't want our deprecations to be ignored by default, | |
# so create our own type. | |
class DeprecatedWarning(UserWarning): | |
pass | |
def deprecated(instructions): | |
"""Flags a method as deprecated. | |
Args: | |
instructions: A human-friendly string of instructions, such | |
as: 'Please migrate to add_proxy() ASAP.' | |
""" | |
def decorator(func): | |
'''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.''' | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
message = 'Call to deprecated function {}. {}'.format( | |
func.__name__, | |
instructions) | |
frame = inspect.currentframe().f_back | |
warnings.warn_explicit(message, | |
category=DeprecatedWarning, | |
filename=inspect.getfile(frame.f_code), | |
lineno=frame.f_lineno) | |
return func(*args, **kwargs) | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment