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:

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

results matching ""

    No results matching ""