decorator needs access to variables where it is used.

Serhiy Storchaka storchaka at gmail.com
Sat Oct 12 15:55:18 EDT 2019


09.10.19 14:02, Chris Angelico пише:
> The decorator has full access to the function object, including a
> reference to that function's module globals.
> 
> def trace(func):
>      log = func.__globals__["log"]
>      ... proceed as before
> 
> As long as you can depend on "log" always being a module-level
> (global) name, and not (for instance) a closure variable, this should
> work. It's a bit ugly, but it should be fine since it's buried away in
> the decorator.

It may be better to not rely on global variable "log", but get the 
logger by the module name.

def trace(func):
     log = logging.getLogger(func.__module__)
     ...




More information about the Python-list mailing list