Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function name of wrapped function? [duplicate]

Tags:

python

How can I get the name of the original function?

def wrap(f):
    def wrapped_f(*args, **kwargs):
        # do something
    return wrapped_f

@wrap
def A(params):
   # do something

print(A.__name__)

result: wrapped_f, but I need A!

like image 551
varantir Avatar asked Jun 12 '15 09:06

varantir


People also ask

What is __ wrapped __ in Python?

__wrapped__ in Python decorators As we can see from the code of the functools module 1, when decorating an object, there is an attribute named __wrapped__ that holds the reference to the original one. So now if we use this, we can access it directly without having to resort to the old quirks.

What is wrapping a function?

A wrapper function is a subroutine (another word for a function) in a software library or a computer program whose main purpose is to call a second subroutine or a system call with little or no additional computation.

What does @wraps do in Python?

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. Parameters: wrapped: The function name that is to be decorated by wrapper function.

What does Functools do in Python?

Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes – partial and partialmethod.


2 Answers

Use functools.wraps():

Straight from the docs:

Without the use of this decorator factory, the name of the example function would have been 'wrapper', and the docstring of the original example() would have been lost.

Example:

from functools import wraps


def wrap(f):
    @wraps(f)
    def wrapped_f(*args, **kwargs):
        pass
    return wrapped_f


@wrap
def A(params):
    pass


print(A.__name__)

Output:

$ python -i foo.py
A
>>> 
like image 70
James Mills Avatar answered Sep 23 '22 13:09

James Mills


Use functools.wraps or update wrapped_f's __name__ attribute manually.

from functools import wraps

def wrap(f):
    @wraps(f)
    def wrapped_f(*args, **kwargs):
        # do something
    return wrapped_f

@wrap
def A(params):
   # do something

print(A.__name__)
like image 27
Alik Avatar answered Sep 26 '22 13:09

Alik