Search code examples
python-3.xpython-decorators

Python - give wrapper function the same name as wrapped function


Is it possible to modify the decorator function

def wrap(function):
    def wrapper(*args, **kwargs):
        print(function.__name__)
        return function(*args, **kwargs)
    return wrapper

to make the code

@wrap
@wrap
@wrap
def hello():
    print("Hello, world!")


hello()

print

hello
hello
hello
Hello, world!

instead of

wrapper
wrapper
hello
Hello, world!

? My aim is to compose several decorators that all rely on the function name.


Solution

  • The following code should work, although I am not quite sure of your intent.

    Anyway, trusting my guts, I would eschew such constructions.

    import functools
    
    def wrap(function):
        @functools.wraps(function)
        def wrapper(*args, **kwargs):
            print(function.__name__)
            return function(*args, **kwargs)
        return wrapper
    
    @wrap
    @wrap
    @wrap
    def hello():
        print("Hello, world!")
    
    hello()