Decorators part 3: @wraps
Date: February 16th 2016
Last updated: February 16th 2016
Why am I was losing my docstrings and function names after using a decorator? I only noticed this happening after evaluating help() on an instantiated object using my module.
The solution is to use the functools module and the @wraps decorator. From the docs: "Without the use of this decorator factory, the name of the example function would have been 'wrapper', [in my example function this would be inner'] and the docstring of the original example() would have been lost."
Useful resources:
- https://docs.python.org/2/library/functools.html
- https://docs.python.org/3/library/functools.html
- http://stackoverflow.com/questions/308999/what-does-functools-wraps-do
import math
from functools import wraps
# decorator to pretty print
def formatter(func):
@wraps(func) #<============== use functools
def inner(*args):
return "{} = {:.2f}".format(func.__name__, func(*args))
return inner
class Circle(object):
def __init__(self, radius):
self.radius = float(radius)
@formatter
def area(self):
return (math.pi * self.radius) ** 2