如何从Python函数中剥离装饰器 [英] How to strip decorators from a function in Python
本文介绍了如何从Python函数中剥离装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下内容:
def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
我想测试垃圾邮件
函数,而无需经历建立连接的麻烦(或装饰者所做的任何事情)。
I want to test the spam
function without going through the hassle of setting up a connection (or whatever the decorator is doing).
给出垃圾邮件
,如何从中剥离装饰器并获得基础的未装饰功能?
Given spam
, how do I strip the decorator from it and get the underlying "undecorated" function?
推荐答案
一般情况下,您不能这样做,因为
In the general case, you can't, because
@with_connection
def spam(connection):
# Do something
等同于
def spam(connection):
# Do something
spam = with_connection(spam)
表示原始 pam可能甚至不存在了。一个(不太漂亮的)黑客是这样的:
which means that the "original" spam might not even exist anymore. A (not too pretty) hack would be this:
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函数中剥离装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文