Doctest and Decorators in Python -
i trying use python decorator catch exceptions , log 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)
it works fine
desktop> python deco.py inside __init__() inside __call__() 1 2 3 sorry
the issue when tried use testing doctest
@log def testit(a, b, c): """ >>> testit(1,2,3) """ print a,b,c raise runtimeerror() if __name__ == "__main__": import doctest doctest.testmod()
nothing seems happening.
desktop> python deco2.py inside __init__()
what's wrong this?
the decorated function (which class instance) doesn't __doc__
attribute of original function (which doctest
parses). could copy __doc__
on class instance, ... honestly, don't see need class @ here -- you'd better using functools.wraps
import functools def log(func): @functools.wraps(func) def wrapper(*args): try: return func(*args) except exception: print "sorry" return wrapper
Comments
Post a Comment