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

前端 未结 4 1093
情歌与酒
情歌与酒 2020-12-29 02:02

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          


        
4条回答
  •  醉话见心
    2020-12-29 02:30

    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.

提交回复
热议问题