Python default argument trap

wrap up

--Default arguments are evaluated only once when defining a function --Be careful because the same instance will be used.

trap

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.

Reason

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

Python default argument trap
Python default argument behavior
Python function argument summary
Python or and and operator trap
Python 2D array trap [Copy array]
Command line argument processing (Python docopt)
[python] Callback function (pass function as argument)
Be careful when specifying the default argument value in Python3 series
Function argument type definition in python
Python
Expansion by argument of python dictionary
Change python default encoding to utf-8
Basic Python operation 2nd: Function (argument)
[Raspberry Pi] Changed Python default to Python3
[Python] Easy argument type check with dataclass
Python strings become f strings by default (maybe)
Sample script to trap signals in Python
⚠️ Be careful with Python's default argument values ⚠️
To set default encoding to utf-8 in python
Make the default value of the argument immutable