【发布时间】:2023-03-07 16:27:02
【问题描述】:
以下代码来自 Matplotlib 的__init__ 文件:
def _logged_cached(fmt, func=None):
"""
Decorator that logs a function's return value, and memoizes that value.
After ::
@_logged_cached(fmt)
def func(): ...
the first call to *func* will log its return value at the DEBUG level using
%-format string *fmt*, and memoize it; later calls to *func* will directly
return that value.
"""
if func is None: # Return the actual decorator.
return functools.partial(_logged_cached, fmt)
called = False
ret = None
@functools.wraps(func)
def wrapper(**kwargs):
nonlocal called, ret
if not called:
ret = func(**kwargs)
called = True
_log.debug(fmt, ret)
return ret
return wrapper
问题:上述函数中的缓存是如何工作的? _logged_cached 的局部变量不会在每次调用时重新初始化吗?
据我了解,局部变量在函数返回后被删除(对吗?)。如果是这样,那么缓存将不起作用。然而,文档说装饰函数将在每次调用时返回相同的对象——它确实如此。怎么样?
【问题讨论】:
标签: python matplotlib decorator local-variables