python - 在Python中使用装饰器注入(inject)函数

标签 python function decorator inject

import functools
import logging
def logDeprecated( msg=None, *args, **kwargs ):
    """Log a message at level 'WARNING'

    Args:
        msg=None : (str)
            The message you wish to log.
            If no msg is passed, default to 'This function has been deprecated.'
            All other args are passed directly to logging.Logger.log().

    Keyword Args:
        category : (str)
            The category for the message to be logged.  If not
            specified, then an appropriate category will be
            determined based on the calling context.

        All other keyword args are passed directly to logging.Logger.log().

    Raises:
        n/a

    Returns:
        n/a

    """
    if not msg:
        msg = "This function has been deprecated."

    # Make sure category is stripped from kwargs before passing to log().
    cat = kwargs.pop('category', None)
    if not cat:
        cat = _getLoggingCategory()
    cat = "{0}.DEPRECATED".format(cat)

    logging.getLogger( category=cat ).log( logging.WARNING, msg, *args, **kwargs )

def decoratedLogDeprecated(func):
    def thisFunc(*args, **kwargs):
        func(*args, **kwargs)
        logDeprecated()
    return wraps(func)(thisFunc)

@decoratedLogDeprecated
def somefunc():
    print "This used to work"

def main():
    somefunc()

if __name__ == 'main':
    main()

正在记录的行号是 main 中的行号。实际上,它应该报告实际函数中的行号。

有没有办法使用装饰器将该函数注入(inject)到被装饰的函数中?我们将不胜感激所有的帮助。

最佳答案

以下是获取定义行号和调用行号的方法

from functools import wraps
def decoratedLogDeprecated(func):
    import inspect
    l = inspect.stack(1)[1][2]
    def thisFunc(*args, **kwargs):
        print "Defined at line", l
        func(*args, **kwargs)
        logDeprecated()

    return wraps(func)(thisFunc)

def logDeprecated():
    import inspect
    print "Called at line", inspect.stack(2)[2][2]

@decoratedLogDeprecated
def f():
    pass

@decoratedLogDeprecated
def g():
    pass

f()
g()

关于python - 在Python中使用装饰器注入(inject)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13188091/

相关文章:

python - 如何在 matplotlib 中绘制半误差线?

python - readline() 从某个文件运行时不返回任何内容

JavaScript 函数作为对象

python - 更改字典中的数据框

python - 在 sqlalchemy 中的查询级别连接列

.net - WPF 装饰器类有用吗?

python - (python)在函数中使用装饰器进行彩色打印

python - 带参数的装饰器

python - eclipse (pydev) : Is it possible to assign a shortcut to send selection to the python console?

java - 函数是否只存在于非面向对象的语言中?