+ 5

Can you un-decorate a function?

If there is a decorator function: decorator(func) and a function: func1(), and you apply the decorator on func1 by @decorator before the definition, can you still access the original "un-decorated" function somehow?

27th Jan 2022, 6:47 PM
rdhelli
rdhelli - avatar
1 Answer
+ 4
There appears to be a partial 'yes' answer to this question. The update_wrapper function from functools adds a .__wrapped__ attribute which, since Python 3.4 always refers to the wrapped function. Functools further provides a convenience function for update_wrapper, the wraps function. With that you can wrap your functions with custom wrappers and access the unwrapped via .__wrapped__. I have tried the following here in the playground and it works: from functools import wraps def log(f): @wraps(f) def logger(): print("[**LOG**] ", f()) return logger @log def func(): return "This message" print(dir(func)) print(func.__wrapped__()) The first print shows the existence of the .__wrapped__ attribute. The second print prints "This message".
27th Jan 2022, 8:51 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar