Doctest and Decorators in Python

I tried using the Python decorator to detect exceptions and register 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 great

Desktop> python deco.py 
Inside __init__()
Inside __call__()
1 2 3
Sorry

The problem 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()

Nothing happens.

Desktop> python deco2.py 
Inside __init__()

What happened to this?

+4
source share
2 answers

( ) __doc__ ( , doctest). __doc__ , ... , - , , functools.wraps

import functools
def log(func):
    @functools.wraps(func)
    def wrapper(*args):
        try:
            return func(*args)
        except Exception:
            print "sorry"
    return wrapper
+8

docstring :

class log(object):
    def __init__(self, f):
        print "Inside __init__()"
        self.f = f
        self.__doc__ = f.__doc__

    def __call__(self, *args):
        print "Inside __call__()"
        try:
            self.f(*args)
        except Exception:
            print "Sorry"

, docstring .

functools.update_wrapper() , docstring, :

from functools import update_wrapper

class log(object):
    def __init__(self, f):
        print "Inside __init__()"
        self.f = f
        update_wrapper(self, f)

    def __call__(self, *args):
        print "Inside __call__()"
        try:
            self.f(*args)
        except Exception:
            print "Sorry"
+4

Source: https://habr.com/ru/post/1535055/


All Articles