Making a decorator look like the decorated function

suggest change

Decorators normally strip function metadata as they aren’t the same. This can cause problems when using meta-programming to dynamically access function metadata. Metadata also includes function’s docstrings and its name. functools.wraps makes the decorated function look like the original function by copying several attributes to the wrapper function.

from functools import wraps

The two methods of wrapping a decorator are achieving the same thing in hiding that the original function has been decorated. There is no reason to prefer the function version to the class version unless you’re already using one over the other.

As a function

def decorator(func):
    # Copies the docstring, name, annotations and module to the decorator
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapped_func

@decorator
def test():
    pass

test.__name__
‘test’

As a class

class Decorator(object):
    def __init__(self, func):
        # Copies name, module, annotations and docstring to the instance.
        self._wrapped = wraps(func)(self)
        
    def __call__(self, *args, **kwargs):
        return self._wrapped(*args, **kwargs)

@Decorator
def test():
    """Docstring of test."""
    pass

test.__doc__
‘Docstring of test.’

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Decorators:
* Making a decorator look like the decorated function

Table Of Contents
2 Filter
3 List
5 Decorators
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve