While learning about decorator and decorator factories, I checked the source code of the @functools.lru_cache since it allows both usages using one single implementation. And I spotted something that is intriguing me. In the following statement wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed} extracted from this piece of code from the CPython implementation:
def lru_cache(maxsize=128, typed=False):
"""<docstring ommited for brevity>"""
if isinstance(maxsize, int):
# Negative maxsize is treated as 0
if maxsize < 0:
maxsize = 0
elif callable(maxsize) and isinstance(typed, bool):
# The user_function was passed in directly via the maxsize argument
user_function, maxsize = maxsize, 128
wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
return update_wrapper(wrapper, user_function)
elif maxsize is not None:
raise TypeError(
'Expected first argument to be an integer, a callable, or None')
def decorating_function(user_function):
wrapper = _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo)
wrapper.cache_parameters = lambda : {'maxsize': maxsize, 'typed': typed}
return update_wrapper(wrapper, user_function)
return decorating_function
What's the purpose of creating a lambda that only returns a dictionary instead of setting the dictionary directly to the attribute?