I haven't used Python yet, but I was a little addicted to it without knowing the specifications of the default arguments.
Actually, the value specified by the default argument is ** cached **, so if you use ** mutable data ** such as a list or dictionary as the default argument without knowing this, it will behave unintentionally.
#a is the default argument
def hoge(a=[]):
a.append('a')
print(a)
hoge() # ['a']
hoge() # ['a', 'a'] ※['a']is not
If you do the above, the second call to hoge () will result in ['a','a'] instead of a = ['a']. This is because ['a'] after the first call is reused.
Use ** immutable ** values such as None, numbers, strings, and tuples as default arguments.
If you really want to use a list or dictionary as the default argument, use the following method.
def hoge(a=None):
if a is None:
a = []
a.append('a')
print(a)
hoge() # ['a']
hoge() # ['a']
Recommended Posts