3 ms·
I've tried to see __defaults__ and __kwdefaults__ here: i = 7 lambda_list = [lambda: i for i in range(3)] results = [x() for x in lambda_list]
by acqq 3y ago
I've tried to see __defaults__ and __kwdefaults__ here:
i = 7
lambda_list = [lambda: i for i in range(3)]
results = [x() for x in lambda_list]
print( i )
for k in range( 3 ):
print( lambda_list[k] )
print( lambda_list[k].__defaults__ )
print( lambda_list[k].__kwdefaults__ )
lambda_list = [lambda j=i: j for i in range(3)]
results = [x() for x in lambda_list]
print( i )
for k in range( 3 ):
print( lambda_list[k] )
print( lambda_list[k].__defaults__ )
print( lambda_list[k].__kwdefaults__ )
print( i )
The output is:
7
<function <listcomp>.<lambda> at 0xB2>
None
None
<function <listcomp>.<lambda> at 0xBC>
None
None
<function <listcomp>.<lambda> at 0xC6>
None
None
7
<function <listcomp>.<lambda> at 0xD0>
(0,)
None
<function <listcomp>.<lambda> at 0xDA>
(1,)
None
<function <listcomp>.<lambda> at 0xE4>
(2,)
None
7
If I understand it, __kwdefaults__ are always None and the __defaults__ used only in the second case. I've also tried to see the "i" as not being inside of the closure, but it remains 7, not like (as noted by 'remram here):
i = 9
y = 1
for y in range( 1,-1,-1 ):
try:
x = 4 / y
except Exception as i:
pass
print( i )
Which gives, for me, fascinating:
9
Traceback (most recent call last):
File "p.py", line 10, in <module>
print( i )
^
NameError: name 'i' is not defined. Did you mean: 'id'?
I'm learning a lot here.
- quietbritishjim 3y agoOops, `__kwdefaults__` is only for keyword-only arguments fn = lambda x, *args, y=3: 0 print(fn.__defaults__, fn.__kwdefaults__) # prints None {'y': 3} Source: https://stackoverflow.com/questions/17533929/what-is-the-use-of-kwdefaults-which-is-a-function-object-attribute https://stackoverflow.com/questions/17533929/what-is-the-use...