Decorator debugging help (Python)

vegaseat 1 Tallied Votes 433 Views Share

If you decorate a function, then some of the information is lost during the debugging process. Python supplies another decorator @wraps to help out. A decorator for a decorator, very interesting.

''' wraps_decorator.py
using the @wraps decorator on a decorator's inner function
is very helpful during debugging
tested with Python27 and Python33  by  vegaeeat  12dec2013
'''

from functools import wraps

def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        print('Calling decorated function')  # test
        return f(*args, **kwds)
    return wrapper

@my_decorator
def example():
    """Docstring for function example()"""
    print('Called example function')

# testing
example()
print("example.__name__ = {}".format(example.__name__))
print("example.__doc__ = {}".format(example.__doc__))

'''
result with @wraps ...
Calling decorated function
Called example function
example.__name__ = example
example.__doc__ = Docstring for function example()

result without @wraps ...
Calling decorated function
Called example function
example.__name__ = wrapper
example.__doc__ = None
'''