Python | functools.wraps() function
Last Updated :
23 Sep, 2021
functools is a standard Python module for higher-order functions (functions that act on or return other functions). wraps() is a decorator that is applied to the wrapper function of a decorator. It updates the wrapper function to look like wrapped function by copying attributes such as __name__, __doc__ (the docstring), etc.
Syntax: @functools.wraps(wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES)
Parameters:
wrapped: The function name that is to be decorated by wrapper function.
assigned : Tuple to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function. By default set to WRAPPER_ASSIGNMENTS (which assigns to the wrapper function’s __module__, __name__, __qualname__, __annotations__ and __doc__, the documentation string)
updated : Tuple to specify which attributes of the wrapper function are updated with the corresponding attributes from the original function. By default set to WRAPPER_UPDATES (which updates the wrapper function’s __dict__, i.e. the instance dictionary).
Example 1: Without functools.wraps()
Python3
def a_decorator(func):
def wrapper(*args, **kwargs):
"""A wrapper function"""
# Extend some capabilities of func
func()
return wrapper
@a_decorator
def first_function():
"""This is docstring for first function"""
print("first function")
@a_decorator
def second_function(a):
"""This is docstring for second function"""
print("second function")
print(first_function.__name__)
print(first_function.__doc__)
print(second_function.__name__)
print(second_function.__doc__)
Output:wrapper
A wrapper function
wrapper
A wrapper function
Now what will happen if we write help(first_function) and help(second_function)
Python3
print("First Function")
help(first_function)
print("\nSecond Function")
help(second_function)
Output: First Function
Help on function wrapper in module __main__:
wrapper(*args, **kwargs)
A wrapper function
Second Function
Help on function wrapper in module __main__:
wrapper(*args, **kwargs)
A wrapper function
While the above code will work logically fine, but consider this if you are writing an API or a library and someone want to know what your function does and it's name or simply type help(yourFunction), it will always show wrapper function's name and docstring. This gets more confusing if you have used the same wrapper function for different functions, as it will show the same details for each one of them.
Ideally it should show the name and docstring of wrapped function instead of wrapping function. Manual solution would be to assign __name__, __doc__ attributes in the wrapping function before returning it.
Python3
def a_decorator(func):
def wrapper(*args, **kwargs):
"""A wrapper function"""
# Extend some capabilities of func
func()
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
return wrapper
@a_decorator
def first_function():
"""This is docstring for first function"""
print("first function")
@a_decorator
def second_function(a):
"""This is docstring for second function"""
print("second function")
print(first_function.__name__)
print(first_function.__doc__)
print(second_function.__name__)
print(second_function.__doc__)
Output:first_function
This is docstring for first function
second_function
This is docstring for second function
This solves the problem, but what if we again type help(yourFunction),
Python3
print("First Function")
help(first_function)
print("\nSecond Function")
help(second_function)
For first_function: help(first_function)
Output: First Function
Help on function first_function in module __main__:
first_function(*args, **kwargs)
This is docstring for first function
Second Function
Help on function second_function in module __main__:
second_function(*args, **kwargs)
This is docstring for second function
As you can see it still has an issue, i.e. the signature of the function, it is showing signature used by wrapper function (here, generic signature) for each of them. Also if you are implementing many decorators, then you have to write these lines for each one of them.
So to save time and increase readability, we could use functools.wraps() as decorator to wrapper function.
Example (with functools.wraps())
Python3
from functools import wraps
def a_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
"""A wrapper function"""
# Extend some capabilities of func
func()
return wrapper
@a_decorator
def first_function():
"""This is docstring for first function"""
print("first function")
@a_decorator
def second_function(a):
"""This is docstring for second function"""
print("second function")
print(first_function.__name__)
print(first_function.__doc__)
print(second_function.__name__)
print(second_function.__doc__)
Output: first_function
This is docstring for first function
second_function
This is docstring for second function
Now, if we type help(first_function) -
Python3
print("First Function")
help(first_function)
print("\nSecond Function")
help(second_function)
Output: First Function
Help on function first_function in module __main__:
first_function()
This is docstring for first function
Second Function
Help on function second_function in module __main__:
second_function(a)
This is docstring for second function
Similar Reads
Function Wrappers in Python
Function wrappers, also known as decorators, are a powerful and useful feature in Python that allows programmers to modify the behavior of a function or class without changing its actual code. Decorators enable wrapping another function to extend or alter its behavior dynamically at runtime.Example:
2 min read
vars() function in Python
vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be a module, a class, an instance, or access the __dict__ attribute in Python. In this article, we will learn more about vars() function in Python. Python vars() Function Syntax Syntax: vars(
3 min read
locals() function-Python
locals() function in Python returns a dictionary representing the current local symbol table, allowing you to inspect all local variables within the current scope e.g., inside a function or block. Example:Pythondef fun(a, b): res = a + b print(locals()) fun(3, 7)Output{'a': 3, 'b': 7, 'res': 10} Exp
4 min read
type() function in Python
The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
Python - globals() function
In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope. This function is particularly useful when you want to in
2 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
Python Functools - update_wrapper()
The functools module in Python deals with higher order functions, that is, functions operating on(taking as arguments) or returning functions and other such callable objects. The functools module provides a wide array of methods such as cached_property(func), cmp_to_key(func), lru_cache(func), wraps
6 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
11 min read
Python str() function
The str() function in Python is an in-built function that takes an object as input and returns its string representation. It can be used to convert various data types into strings, which can then be used for printing, concatenation, and formatting. Letâs take a simple example to converting an Intege
3 min read
Python User Defined Functions
A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency.Example:Python# function defination def
6 min read