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

Jack Z picture Jack Z · Mar 2, 2012 · Viewed 19.8k times · Source

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?

Answer

Sven Marnach picture Sven Marnach · Mar 2, 2012

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.