Lifetime of default function arguments in python

This question already has an answer here:

  • “Least Astonishment” and the Mutable Default Argument 30 answers

  • As the argument is an attribute of the function object, it normally has the same lifetime as the function. Usually, functions exist from the moment their module is loaded, until the interpreter exits.

    However, Python functions are first-class objects and you can delete all references (dynamically) to the function early. The garbage collector may then reap the function and subsequently the default argument:

    >>> def foo(bar, spam=[]):
    ...     spam.append(bar)
    ...     print(spam)
    ... 
    >>> foo
    <function foo at 0x1088b9d70>
    >>> foo('Monty')
    ['Monty']
    >>> foo('Python')
    ['Monty', 'Python']
    >>> foo.func_defaults
    (['Monty', 'Python'],)
    >>> del foo
    >>> foo
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'foo' is not defined
    

    Note that you can directly reach the func_defaults attribute ( __defaults__ in python 3), which is writable, so you can clear the default by reassigning to that attribute.


    It has at least the same lifetime as the function object (absent something funky). Accordingly, if the module it was loaded from is unloaded by all other modules, and there are no other references, then the function object, and its members, will likely be destroyed.

    Because Python is garbage collected, you don't really need to worry about this in any practical sense. If the object escapes, and some other part of the programme has a reference, it will hang around.

    If your point is that you would like to rely on the object hanging around and not being reset, then yes, you can do that, unless you have something funky unloading modules, or if you have some code assigning to variable on the function object which stores the default value.

    链接地址: http://www.djcxy.com/p/28540.html

    上一篇: 将一个列表传递给一个类python

    下一篇: 在Python中默认函数参数的生命周期