I have a Python function that takes a list as a parameter. If I set the parameter's default value to an empty list like this:
def func(items=[]): print items
Pylint would tell me "Dangerous default value [] as argument". So I was wondering what is the best practice here?
Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.
The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
We can provide a default value to a particular argument in the middle of an argument list.
Answer: d) is a bad idea because the default [] will accumulate data and the default [] will change with subsequent calls.
Use None
as a default value:
def func(items=None): if items is None: items = [] print items
The problem with a mutable default argument is that it will be shared between all invocations of the function -- see the "important warning" in the relevant section of the Python tutorial.
I just encountered this for the first time, and my immediate thought is "well, I don't want to mutate the list anyway, so what I really want is to default to an immutable list so Python will give me an error if I accidentally mutate it." An immutable list is just a tuple. So:
def func(items=()): print items
Sure, if you pass it to something that really does want a list (eg isinstance(items, list)), then this'll get you in trouble. But that's a code smell anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With