Python中的Doctest和Decorators [英] Doctest and Decorators in Python
本文介绍了Python中的Doctest和Decorators的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用Python装饰器来捕获异常并记录异常.
I was trying to use Python decorator to catch exceptions and log the exceptions.
import os.path
import shutil
class log(object):
def __init__(self, f):
print "Inside __init__()"
self.f = f
def __call__(self, *args):
print "Inside __call__()"
try:
self.f(*args)
except Exception:
print "Sorry"
@log
def testit(a, b, c):
print a,b,c
raise RuntimeError()
if __name__ == "__main__":
testit(1,2,3)
工作正常
Desktop> python deco.py
Inside __init__()
Inside __call__()
1 2 3
Sorry
问题是,当我尝试用于doctest进行测试
The issue is that when I tried to use for testing with doctest
@log
def testit(a, b, c):
"""
>>> testit(1,2,3)
"""
print a,b,c
raise RuntimeError()
if __name__ == "__main__":
import doctest
doctest.testmod()
似乎什么都没发生.
Desktop> python deco2.py
Inside __init__()
这是怎么了?
推荐答案
修饰后的函数(实际上是一个类实例)没有获得原始函数的 __ doc __
属性(即 doctest
进行解析).您可以将 __ doc __
复制到类实例中,但是...老实说,我真的没有真正在这里看到类的需要-您会仅使用 functools.wraps
The decorated function (which is actually a class instance) doesn't get the __doc__
attribute of the original function (which is what doctest
parses). You could just copy __doc__
over to the class instance, but ... Honestly, I don't really see the need for a class at all here -- you'd probably be better just using functools.wraps
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args):
try:
return func(*args)
except Exception:
print "sorry"
return wrapper
这篇关于Python中的Doctest和Decorators的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文