Python Default Parameters Tripped Me Up
Python default parameters might be changed with each run
As one might need default parameters in python functions, such as
def func(inp = []):
inp.append(1)
return inp
they might cause trouble. Python functions are objects of a certain identity. Every time you run it, the input inp
changes. The consequence is that the function returns different results.
A better strategy is to use None
. Here is an example:
def func(inp = None):
if inp is None:
inp = []
return inp
For references, please read: Default Parameter Values in Python.
Planted:
by Lei Ma;
References:
Similar Articles:
L Ma (2017). 'Python Default Parameters Tripped Me Up', Datumorphism, 06 April. Available at: https://datumorphism.leima.is/til/programming/python/python-default-parameters-mutable/.