One point to note with the default value of argument in Python

Tram Ho

Source: https://qiita.com/yukinoi/items/57f6150c5d805d4b25e4

Things to note with Python’s default argument values.

Recently I had a problem with Python’s default argument values ​​working at will. Now I write this article to share information to help this incident not happen to you. The environment is Python 3.7.7 and 3.8.3.

What is the default argument value? For example, in the following code, the default argument value is dt = datetime.now ()

Trap of Python’s default argument value In the code above, we called the show_second function once. I set it to three seconds and then call the show_second function again.

What happened then? Despite the 3-second sleep, but when calling the show_second function a second time, the value is still the same as 3 seconds ago. Time stops? Or is it Za Warudo? Or use Arate’s Stand? (reference JoJo Bizzare Adventure comic series)

Operation of the default Python argument value

I have looked in the Python document and found the following: The default argument value, when performing the function definition, will evaluate from left to right.

In other words, the default argument value is estimated once at the time the function is determined, the result is stored in memory, and if the default argument value is used no matter how many times the function is called, Evaluation results at the time of determining the function used. It seems to work.

So it’s risky to use something like datetime.now () to yield different results every time you call and / or something that requires real-time calculation as the default argument value.

Similarly, you need to be careful when specifying lists or dictionaries as default argument values. (How to use default arguments in Python functions and notes | note.nkmk.me )

Measures against default argument values ​​in Python

So what to do is to set No as the default argument value, and if there is no value, it seems better to replace the original value you want to be set as the default argument value.

Here is an example.

Above is the content of things to note about the default Python argument.

Share the news now

Source : Viblo