def suppress(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
pass
return wrapper
def myfunc():
print("foo")
print("foo")
我在一本书中找到了这段代码,然后按照它说的那样运行...
suppress(myfunc)
该书说它应该运行该函数,但可以抑制其中的错误,该错误在
print("foo")
中相反,它给了我...
<function myfunc at 0x6981e0>
为什么???
最佳答案
您的suppress
函数被设计为装饰器,因此您需要将其应用于函数/方法。惯用的方法是使用@
语法,就像使用functools.wraps
一样。
import functools
def suppress(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
pass
return wrapper
@suppress # <-------- this is the idiomatic fix
def myfunc():
"documentation"
print("foo")
raise ValueError
def myfunc2():
"documentation"
print("foo")
raise ValueError
myfunc() # prints "foo", does not raise exception
print myfunc.__doc__ # prints "documentation"
suppress(myfunc2)() # functional style; prints "foo", does not raise exception
print suppress(myfunc2).__doc__ # prints "documentation"
关于python - 包装函数Python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9949678/