def memo_square(a, cache={}): if a not in cache: cache[a] = a*a return cache[a]
memo_square
(like any other function) is an object of the function class, which, among other attributes, has a memo_square.__defaults__
tuple memo_square.__defaults__
is filled in when the object is memo_square.__defaults__
. First, it contains an empty dictionary, as indicated in the function header: >>> memo_square.__defaults__ ({},)
__defaults__
is a regular tuple and its elements cannot be changed. You can, however, replace the entire set of default values at once, but only on a different tuple: >>> def test(a=1, b=2): ... print(a, b) ... >>> test.__defaults__ (1, 2) >>> test() 1 2 >>> test.__defaults__ = (', ', '') >>> test() , >>> test.__defaults__[1] = '' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> test.__defaults__ = {0: ', ', 1: ''} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __defaults__ must be set to a tuple object
func.__defaults__
is created once during the work of the program along with all its elements. The tuple and its elements will not be recreated with each function call, they will be used as long as the function exists. But to change, if the elements themselves are mutable, nobody forbids them. The inability to work with such elements is one of the most common ways to shoot yourself in the foot in python . But in general, storing values between function calls can be quite useful. After several calls, memo_square.__defaults__
will look like this: >>> memo_square(2) 4 >>> memo_square.__defaults__ ({2: 4},) >>> memo_square(5) 25 >>> memo_square.__defaults__ ({2: 4, 5: 25},) >>> memo_square(2) 4 >>> memo_square.__defaults__ ({2: 4, 5: 25},)
def square(a): return a**a cache = {} for x in values: if x not in cache: cache[x] = x**x print cache[x]
func.__defaults__
, which is rather difficult to access by mistake.Source: https://habr.com/ru/post/426341/
All Articles