Lifetime of default function arguments in python -


this question has answer here:

i started learning python, got struck default argument concept.

it mentioned in python doc default argument value of function computed once when def statement encountered. makes large difference between values of immutable , mutable default function arguments.

>>> def func(a,l=[]):       l.append(a)       return l >>> print(func(1)) [1] >>> print(func(2)) [1, 2] 

here mutable function argument l retains last assigned value (since default value calculated not during function call in c)

is lifetime of default argument's value in python lifetime of program (like static variables in c) ?

edit :

>>> lt = ['a','b'] >>> print(func(3,lt)) ['a', 'b', 3] >>> print(func(4)) [1, 2, 4] 

here during function call func(3,lt) default value of l preserved, not overwritten lt.

so default argument have 2 memory? 1 actual default value (with program scope) , other when object passed (with scope of function call)?

as argument attribute of function object, has same lifetime function. usually, functions exist moment module loaded, until interpreter exits.

however, python functions first-class objects , can delete references (dynamically) function early. garbage collector may reap function , subsequently default argument:

>>> def foo(bar, spam=[]): ...     spam.append(bar) ...     print(spam) ...  >>> foo <function foo @ 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' not defined 

note can directly reach func_defaults attribute (__defaults__ in python 3), writable, can clear default reassigning attribute.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -