avatarSunil Kumar

Summarize

What is functools.wraps ??

What is a python Decorator?

A decorator is a function that takes another function as its argument and extends its behavior without explicitly modifying that function. In other words, Decorators allow the extension of an existing function, without any modification to the original function source code.

Let's see it with an example

Without functools.wraps

def decorator(f):
    def wrapper(*args, **kwds):
        """ Wrapper Docstring"""
        print('Calling decorated function')
        return f(*args, **kwds)
    return wrapper
@decorator
def example():
    """Docstring"""
    print('Called example function')

Output:

example()
>> Calling decorated function
>> Called example function
example.__name__
>> 'wrapper'
example.__doc__
>> ' wrapper Docstring'

With functools.wraps

from functools import wraps
def decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
        """ wrapper Docstring"""
        print('Calling decorated function')
        return f(*args, **kwds)
    return wrapper
decorator
def example():
    """Docstring"""
    print('Called example function')

Output:

example()
>> Calling decorated function
>> Called example function
example.__name__
>> 'example'
example.__doc__
>> 'Docstring'

you can see that without the use of this decorator factory, the name of the example function is 'wrapper'and the docstring of the original example() is lost as it is showing the doc string of the wrapper function.

However, with the use of this decorator factory, we get the actual name of the function and its doc string.

Conclusion :

functools.wraps help us to write better decorator.

Reference :

Python
Python3
Python Programming
Recommended from ReadMedium