nikhil <nik....@gmail.com> wrote:

Hi,

I am learning Python and came across this example in the Python Online
Tutorial (
http://docs.python.org/tutorial/controlflow.html#default-argument-values)
for Default Argument Values.

ex:

def  func(a, L=[ ]):
L.append(a)
return L

print func(1)
print func(2)
print func(3)

*O/P*
[1]
[1,2]
[1,2,3]

Now my doubt is,

1)  After the first function call, when ' L' (Reference to List object) goes
out of scope, why isn't it  destroyed ?

2) It seems that this behavior is similar to static variable logic in C
language.  Is it something similar ? OR
    Is it related to scope rules in Python ?


The L parameter is a default parameter. That's a formal parameter with an initial value (L=[]). The reference for that value is established when the definition is executed, not when the function is called. The net effect when the function is at top-level is similar to a static variable in C. But it's not really L that is retained, but the object its bound to. Perhaps it's easiest to think that the function object has a reference to the same object, and copies it to L each time the function is called without that particular formal parameter.

See the online help (this one's for 2.6.2, but other recent versions are the same): http://www.python.org/doc/2.6.2/reference/compound_stmts.html#function-definitions

Usually, you want to make such an initial value a non-mutable value, such as None, 42, or "". But if it's mutable, it will indeed retain its value from one call to the next of that function. As you observed.

There are times when this behavior is useful (eg. nested definitions), and I think it's permanently established in the lanaguage. But it is perhaps one of the most common beginner confusions. And it's part of the solution to some of the other common problems.


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to