Things to watch out for when using default arguments in Python

Introduction

I haven't used Python yet, but I was a little addicted to it without knowing the specifications of the default arguments.

The value specified by the default argument is cached

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.

solution

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

Things to watch out for when using default arguments in Python
Things to watch out for when naming dynamic routing in nuxt.js
Things to watch out for when creating a Python environment on a Mac
Things to watch out for when migrating with Django
Things to keep in mind when using Python for those who use MATLAB
Things to keep in mind when using Python with AtCoder
Things to keep in mind when using cgi with python.
Precautions when giving default values to arguments in Python function definitions
Things to keep in mind when developing crawlers in Python
How to take multiple arguments when doing parallel processing using multiprocessing in python
Things to keep in mind when copying Python lists
Things to note when initializing a list in Python
How to exit when using Python in Terminal (Mac)
Things to keep in mind when processing strings in Python2
Things to keep in mind when processing strings in Python3
Things to keep in mind when building automation tools for the manufacturing floor in Python
Precautions when using pit in Python
When using regular expressions in Python
Effective Python Note Item 17 Respect for certainty when using iterators for arguments
To set default encoding to utf-8 in python
[python, multiprocessing] Behavior for exceptions when using multiprocessing
2015-03-25 python> Multi-line comment> Watch out for indent
Precautions when using for statements in pandas
Log in to Slack using requests in Python
Notes for using python (pydev) in eclipse
A useful note when using Python for the first time in a while
How to receive command line arguments in Python
Automatically register function arguments to argparse in Python
Try to calculate RPN in Python (for beginners)
Error when trying to install psycopg2 in Python
Three things I was addicted to when using Python and MySQL with Docker
Tool to make mask image for ETC in Python
[For beginners] How to use say command in python!
Directory structure for test-driven development using pytest in python
[AWS IoT] Register things in AWS IoT using the AWS IoT Python SDK
How to run python in virtual space (for MacOS)
Initial settings when using the foursquare API in python
Error due to conflict between python when using gurobi
Set constructor keyworded arguments to mock attributes in Python
What to do when Python starts up in Anaconda does not come out unexpectedly
Where to fix code when using plotly for free
Articles to see when installation for Python + OpenCV fails
How to retrieve multiple arrays using slice in python.
When you want to plt.save in a for statement
How to execute a command using subprocess in Python
[Introduction to Python] How to write repetitive statements using for statements
Watch out for randint
What I was addicted to when using Python tornado
When will the default arguments be bound in python? When variables are bound in closure lazy evaluation.
I want to do something in Python when I finish
I know? Data analysis using Python or things you want to use when you want with numpy
[For beginners of competitive pros] Three input methods to remember when starting competitive programming in Python
How to find the cumulative sum / sum for each group using DataFrame in Spark [Python version]
Try to make it using GUI and PyQt in Python
Convert from Pandas DataFrame to System.Data.DataTable using Python for .NET
A simple way to avoid multiple for loops in Python
A memo when creating a directed graph using Graphviz in Python
How to define multiple variables in a python for statement
Tips for coding short and easy to read in Python
How to specify Cache-Control for blob storage in Azure Storage in Python
Useful tricks related to list and for statements in Python