Make the default value of the argument immutable (article explanation)

I will explain this article so that you can understand it. Please forgive me though I will write the same content. https://qiita.com/yuku_t/items/fd517a4c3d13f6f3de40

You can set default values for arguments in function definitions and class init. At this time, if the type of the argument to which the initial value is given is a mutable type, it may not be good.

Function with initial value(Bad example).py


def foo(bar=[]): #List type is mutable, be careful!
    bar.append('baz')
    print(bar)

If you do this with the default values

Run.py


>>> foo()
['baz']
>>> foo()
['baz', 'baz'] #that?

The result has changed. The reason for this is that in Python, the default value of a function is allocated memory when the function is defined. In the above, since the append operation was performed twice for the List type created when the function was defined, two "baz" were included.

To clear this problem In other words, if you want to give an initial value to a mutable type argument without any problem, you can allocate memory when calling the function, not when defining the function. That is, the initialization is performed inside the function.

Function with initial value(Good example).py


def foo(bar=None):
    if bar is None:
        bar = []
    bar.append('baz')
    return bar

It is okay to give an initial value to the immutable type argument. Reference: https://qiita.com/makotoo2/items/fc3a617882916f9775f5

Recommended Posts

Make the default value of the argument immutable (article explanation)
Make the default value of the argument immutable
The timing when the value of the default argument is evaluated is different between Ruby and Python.
Code that sets the default value in case of AttributeError
Find the definition of the value of errno
Make SIP Server as concise as possible (in the middle of explanation)
Be careful when specifying the default argument value in Python3 series
If you give a list with the default argument of the function ...
Make the default interactive shell IPython
About the return value of the histogram.
Supplement to the explanation of vscode
I personally chewed the explanation article of the section DP (Dharma doll drop)
The story of making an immutable mold
Get the value of the middle layer of NN
Watch out for the return value of __len__
The value of pyTorch torch.var () is not distributed
Try singular value decomposition of the daimyo matrix
Find the divisor of the value entered in python
Fix the argument of the function used in map
Search by the value of the instance in the list
Make progress of dd visible in the progress bar
About the * (asterisk) argument of python (and itertools.starmap)
Isn't there a default value in the dictionary?
The world's most easy-to-understand explanation of how to make a LINE BOT (1) [Account preparation]