--Default arguments are evaluated only once when defining a function --Be careful because the same instance will be used.
It is a story that there is a trap to pass the value of the reference system to the default argument.
def hoge(lst=[]):
lst.append('hoge')
print(lst)
hoge()
hoge()
Since lst is an empty array by default, you'll see ['hoge']
twice.
Execution result
['hoge']
['hoge', 'hoge']
The second time, 2 hoge is attached.
Let's change the previous code a little and do this.
def called():
print('called!')
return []
def hoge(lst=called()):
lst.append('hoge')
print(lst)
hoge()
hoge()
The result is like this.
Execution result
called!
['hoge']
['hoge', 'hoge']
By the way, called is displayed without hoge ().
In other words, it seems that the value of the default argument is called and generated only once when the function is defined, and the already generated value is reused when the function is called.
As shown above, it seems that the pattern that "[]
is given as the default argument and the instance of the list is shared by all function calls that do not specify the argument" seems to be common.
I'm sorry if it's common sense.
Recommended Posts