Last active
August 29, 2015 13:56
-
-
Save JobsDong/8950699 to your computer and use it in GitHub Desktop.
deprecated装饰器 based on (http://hychen.wuweig.org/blog/2011/12/18/recipe-deprecated-function-in-python/)
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
#!/usr/bin/python | |
#-*- coding=utf-8 -*- | |
"""用于描述一些具体的方法 | |
""" | |
__author__ = ['"wuyadong" <[email protected]>'] | |
import warnings | |
import functools | |
# enable to show warring | |
warnings.simplefilter('default') | |
def deprecated(replacement=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. | |
ref: | |
- recipe-391367-1 on active stack code | |
- recipe-577819-1 on active stack code | |
@replacement function replacement function | |
""" | |
def wrapper(old_func): | |
wrapped_func = replacement and replacement or old_func | |
@functools.wraps(wrapped_func) | |
def new_func(*args, **kwargs): | |
msg = "Call to deprecated function %(funcname)s." % { | |
'funcname': old_func.__name__} | |
if replacement: | |
msg += "; use {} instead".format(replacement.__name__) | |
warnings.warn_explicit(msg, | |
category=DeprecationWarning, | |
filename=old_func.func_code.co_filename, | |
lineno=old_func.func_code.co_firstlineno + 1 | |
) | |
return wrapped_func(*args, **kwargs) | |
return new_func | |
return wrapper | |
def new1(): | |
print 'called new1' | |
@deprecated() | |
def old1(): | |
print 'called old1' | |
@deprecated(new1) | |
def old2(): | |
print 'called old1' | |
if __name__ == '__main__': | |
old1() | |
old2() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment