python - Using a decorated function as a function's default argument -
consider module:
#mymodule.py import logging def print_start_end(name): """ decorator creates logger , logs start , end of function call """ def decorator(f): logger = logging.getlogger(name) def wrapper(*args, **kwargs): logger.info("start") res = f(*args, **kwargs) logger.info("end") return res return wrapper return decorator @print_start_end(__name__) def f(x): return x def g(y=f(3)): return y
and example script:
import logging mymodule import f logger = logging.getlogger("") logger.setlevel(logging.info) h = logging.streamhandler() h.setlevel(logging.info) logger.addhandler(h) print f(3)
output:
start end 3
the decorator working. write script use g
instead of f
:
import logging mymodule import g logger = logging.getlogger("") logger.setlevel(logging.info) h = logging.streamhandler() h.setlevel(logging.info) logger.addhandler(h) print g()
output:
3
when executing statement print g()
, call f
successful because printed expected return value 3. why doesn't print "start" , "end"?
note f(3)
in def g(y=f(3)):
executed once, when function defined, not every time when called.
thus, problem seems time f(3)
executed in mymodule
, logger not yet initialized. initialize first, import, works:
import logging logger = logging.getlogger("") logger.setlevel(logging.info) h = logging.streamhandler() h.setlevel(logging.info) logger.addhandler(h) mymodule import g print g()
Comments
Post a Comment