Why is the empty dictionary a dangerous default value in Python?

This question already has an answer here:

  • “Least Astonishment” and the Mutable Default Argument 30 answers
  • Python methods: default parameter values are evaluated ONCE 3 answers

  • It's dangerous only if your function will modify the argument. If you modify a default argument, it will persist until the next call, so your "empty" dict will start to contain values on calls other than the first one.

    Yes, using None is both safe and conventional in such cases.


    Let's look at an example:

    def f(value, key, hash={}):
        hash[value] = key
        return hash
    
    print f('a', 1)
    print f('b', 2)
    

    Which you probably expect to output:

    {'a': 1}
    {'b': 2}
    

    But actually outputs:

    {'a': 1}
    {'a': 1, 'b': 2}
    
    链接地址: http://www.djcxy.com/p/28518.html

    上一篇: Python函数中的可选参数及其默认值

    下一篇: 为什么空字典在Python中是一个危险的默认值?