好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

如何从Python中的函数中剥离装饰器

假设我有以下内容:

def with_connection(f):
    def decorated(*args, **kwargs):
        f(get_connection(...), *args, **kwargs)
    return decorated

@with_connection
def spam(connection):
    # Do something

我想测试垃圾邮件功能,而不必经历设置连接的麻烦(或者装饰者正在做的任何事情).

鉴于垃圾邮件,如何从中删除装饰器并获得底层的“未修饰”功能?

在一般情况下,你不能,因为

@with_connection
def spam(connection):
    # Do something

相当于

def spam(connection):
    # Do something

spam = with_connection(spam)

这意味着“原始”垃圾邮件可能甚至不再存在.一个(不太漂亮)黑客将是这样的:

def with_connection(f):
    def decorated(*args, **kwargs):
        f(get_connection(...), *args, **kwargs)
    decorated._original = f
    return decorated

@with_connection
def spam(connection):
    # Do something

spam._original(testcon) # calls the undecorated function

查看更多关于如何从Python中的函数中剥离装饰器的详细内容...

  阅读:23次