Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 481
Rastapopoulos Avatar asked Feb 17 '26 04:02

Rastapopoulos


1 Answers

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()