Search code examples
pythondefault-valuepylint

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?


Solution

  • 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.