Make the default value of the argument immutable

You can set the default value of the argument in the function definition

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

Running foo () returns the list ['baz']

>>> foo()
['baz']

Now what if we run the same code again?

>>> foo()
['baz', 'baz']

The result has changed. The reason for this is that Python only evaluates the default value of a function the first time. And the Python list is a mutable object, and ʻappend ()` adds destructive arguments to the list, resulting in unexpected results on the second run. ..

To clear this problem, make immutable objects the default. In the case of the foo function this time

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

To do. No matter how many times this function is called with no arguments, None is immutable, so it returns the same result every time.

>>> foo()
['baz']
>>> foo()
['baz']

In Python, str is immutable, so it's okay to use a string as the default value.

Recommended Posts

Make the default value of the argument immutable
Make the default value of the argument immutable (article explanation)
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
About the return value of pthread_mutex_init ()
Make the default interactive shell IPython
Be careful when specifying the default argument value in Python3 series
If you give a list with the default argument of the function ...
The story of making an immutable mold
Get the value of the middle layer of NN
Watch out for the return value of __len__
Make a copy of the list in Python
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?
[Python of Hikari-] Chapter 06-02 Function (argument and return value 1)
[Python] Calculate the average value of the pixel value RGB of the object
Make a BOT that shortens the URL of Discord
Make a note of the list of basic Pandas usage
[C language] [Linux] Get the value of environment variable
Take the value of SwitchBot thermo-hygrometer with Raspberry Pi
Log the value of SwitchBot thermo-hygrometer with Raspberry Pi
[Golang] Specify an array in the value of map
I examined the argument class_weight of Chainer's softmax_cross_entropy function.
I checked the default OS and shell of docker-machine
[Django] Change the Default IP address of the runserver command
Difference in results depending on the argument of multiprocess.Process
The story that the return value of tape.gradient () was None
[Django 2.2] Sort and get the value of the relation destination
Why is the first argument of [Python] Class self?
The copy method of pandas.DataFrame is deep copy by default
The beginning of cif2cell
Python default argument trap
Make the tool simply
The meaning of self
Python default argument behavior
the zen of Python
The story of sys.path.append ()
Revenge of the Types: Revenge of types
Get the output value of the command (as received by xargs)
Switch the setting value of setting.py according to the development environment
A note on the default behavior of collate_fn in PyTorch
Make the display of Python module exceptions easier to understand
Let's make the analysis of the Titanic sinking data like that
Inherit the standard library to find the average value of Queue
Your URL didn't respond with the value of the challenge parameter.
Find the index of the maximum value (minimum value) of a multidimensional array
Get the value while specifying the default value from dict in Python
[Python3] Call by dynamically specifying the keyword argument of the function
What is the default TLS version of the python requests module?
Extract the value of dict or list as a string
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments