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

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

    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.

提交回复
热议问题