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

前端 未结 4 1095
情歌与酒
情歌与酒 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:33

    For mutable object as a default parameter in function- and method-declarations the problem is, that the evaluation and creation takes place at exactly the same moment. The python-parser reads the function-head and evaluates it at the same moment.

    Most beginers asume that a new object is created at every call, but that's not correct! ONE object (in your example a list) is created at the moment of DECLARATION and not on demand when you are calling the method.

    For imutable objects that's not a problem, because even if all calls share the same object, it's imutable and therefore it's properties remain the same.

    As a convention you use the None object for defaults to indicate the use of a default initialization, which now can take place in the function-body, which naturally is evaluated at call-time.

提交回复
热议问题