Something that seems to have been seen somewhere.
In[1]
def a():
print('a')
f = a
f()
def a():
print('b')
f()
Out[1]
a
a
The same is true for λ.
In[2]
a = lambda: print('a')
f = a
f()
a = lambda: print('b')
f()
Out[2]
a
a
If it is not an assignment, it behaves "intentionally".
In[3]
a = [1]
f = a
print(f)
a.append(1)
print(f)
a = [2]
a.append(2)
print(f)
Out[3]
[1]
[1, 1]
[1, 1]
Details are as commented.
Let's try what happens when we assign it in a function!
In[4]
l = 1
def a():
l = 2
a()
l
Out[4]
1
I failed in sabotage. But using lists can be destructive! dangerous!
In[5]
l = [1]
def a():
l[0] = 2
a()
l[0]
Out[5]
2
Dokan ... The point (?) Of this sabotage is that you can change the contents without passing it as an argument. This is certainly happening when you define variables in a function and use closures.
PyCharm gives a kind message like the following, so I tried it.
Default argument value is mutable
This inspection detects when a mutable value as list or dictionary is detected in a default value for an argument. Default argument values are evaluated only once at function definition time, which means that modifying the default value of the argument will affect all subsequent calls of the function.
In[6]
def a(x=[]):
x.append(1)
return x
a()
a()
a()
Out[6]
[1,1,1]
What! ?? Similarly, the following can be done.
In[7]
def a(x=[0]):
x[0] += 1
return x[0]
a()
a()
a()
Out[7]
3
Recommended Posts