Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for setting the default value of a parameter that's supposed to be a list in Python?

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?

like image 893
Jack Z Avatar asked Mar 02 '12 00:03

Jack Z


People also ask

How do you give a parameter a default value in Python?

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.

How do you set a parameter to default 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.

Where should the default value of parameter is specified?

We can provide a default value to a particular argument in the middle of an argument list.

Why shouldn't you make the default arguments an empty list?

Answer: d) is a bad idea because the default [] will accumulate data and the default [] will change with subsequent calls.


2 Answers

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.

like image 55
Sven Marnach Avatar answered Oct 16 '22 16:10

Sven Marnach


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.

like image 31
sfink Avatar answered Oct 16 '22 18:10

sfink