获取有关在Python装饰器中调用代码的特定信息
我有一个Python装饰器,用于将函数/方法标记为已弃用。它工作得很好,但我希望它工作得更好。具体地说,我希望它能够告诉不推荐使用的函数调用的确切行号。这样一来,人们就不必在源代码中寻找它;相反,警告将直接指向它。(这并不是说有人无论如何都不会通过grep浏览代码来寻找使用call这个不推荐使用的函数的其他地方,但是他们不应该为了响应这样的警告而这样做,IMHO)获取有关在Python装饰器中调用代码的特定信息,python,decorator,Python,Decorator,我有一个Python装饰器,用于将函数/方法标记为已弃用。它工作得很好,但我希望它工作得更好。具体地说,我希望它能够告诉不推荐使用的函数调用的确切行号。这样一来,人们就不必在源代码中寻找它;相反,警告将直接指向它。(这并不是说有人无论如何都不会通过grep浏览代码来寻找使用call这个不推荐使用的函数的其他地方,但是他们不应该为了响应这样的警告而这样做,IMHO) 你不需要这些东西: from functools import wraps import warnings def depreca
你不需要这些东西:
from functools import wraps
import warnings
def deprecated(message, newfunc):
def _deprecated(func):
@wraps(func)
def _wrapped(*args, **kwds):
warnings.warn(message + ', ' + newfunc,
DeprecationWarning, stacklevel=2)
return func(*args, **kwds)
return _wrapped
return _deprecated
就这些!请查看:
@deprecated("function foo is deprecated", "use bar instead")
def foo(bar):
print 'Hello', bar
foo('World')
我明白了
teste.py:17: DeprecationWarning: function foo is deprecated, use bar instead
foo('World')
Hello World
另一个例子:
class Foo(object):
@deprecated("method bar is deprecated", "use baz instead")
def bar(self, baz):
print 'Goodbye', baz
f = Foo()
f.bar('World')
我得到:
teste.py:25: DeprecationWarning: method bar is deprecated, use baz instead
f.bar('World')
Goodbye World
秘密是stacklevel
参数到warnings.warn
。他们说:
stacklevel参数可由用Python编写的包装函数使用,(…)使警告引用deprecation()的调用方,而不是deprecation()本身的源(因为后者会破坏警告消息的目的)
你不需要这些东西:
from functools import wraps
import warnings
def deprecated(message, newfunc):
def _deprecated(func):
@wraps(func)
def _wrapped(*args, **kwds):
warnings.warn(message + ', ' + newfunc,
DeprecationWarning, stacklevel=2)
return func(*args, **kwds)
return _wrapped
return _deprecated
就这些!请查看:
@deprecated("function foo is deprecated", "use bar instead")
def foo(bar):
print 'Hello', bar
foo('World')
我明白了
teste.py:17: DeprecationWarning: function foo is deprecated, use bar instead
foo('World')
Hello World
另一个例子:
class Foo(object):
@deprecated("method bar is deprecated", "use baz instead")
def bar(self, baz):
print 'Goodbye', baz
f = Foo()
f.bar('World')
我得到:
teste.py:25: DeprecationWarning: method bar is deprecated, use baz instead
f.bar('World')
Goodbye World
秘密是stacklevel
参数到warnings.warn
。他们说:
stacklevel参数可由用Python编写的包装函数使用,(…)使警告引用deprecation()的调用方,而不是deprecation()本身的源(因为后者会破坏警告消息的目的)
co_firstlineno目前为您提供了什么?可以使用模块inspect将堆栈升级到调用函数的位置吗?一旦你找到了正确的框架,f_lineno应该告诉你你想要什么——尽管我以前从未在装饰师身上使用过……co_firstlineno目前给了你什么?可以使用模块inspect将堆栈升级到调用函数的位置吗?一旦你找到了正确的框架,f_lineno应该会告诉你你想要什么——尽管我以前从未在装饰师身上使用过……太棒了!非常感谢。(很抱歉,我没早点看到这个,我忘了检查邮箱,结果我不得不做一大堆其他的事情,所以我有一段时间没来这里了…)太棒了!非常感谢。(很抱歉,我没早点看到,我忘了检查邮箱,结果我不得不做一大堆其他事情,所以我有一段时间没来这里了……)