[Tutor] Question about local scopes (namespaces)

Adam Pridgen atpridgen at mail.utexas.edu
Wed Feb 21 19:02:02 CET 2007

Sorry for the long email, and thanks in advance.

In the below example, is the list foo supposed to retain the value
after the function, Bar(), returns?

Is the list foo supposed to reinitialized on each call to Bar(),
meaning len(foo) == 0, and when Bar() returns len(foo) (when Bar() is
called w/out parameters)?

In the example, Bar() is called multiple times, and for the first
three times, I expect foo to initialized as an empty list.  When I
call Bar() and make the assignment however, it turns out that foo is
not reinitialized and it acts like a statically type variable in C or
Java (e.g. retaining its value from each call and subsequent
execution).  I would have expected only one instance of the string in
f after it is assigned the name of foo, however there are four.

My understanding of the code below is as follows:
--If Bar is called without any parameters, then foo is initialized as
an empty list, always.
--If Bar is called with a list parameter, then the name foo is aliased
to that object.
--In the last two cases, if Bar() returns a value to an assignment,
the list will be aliased to that variable name as well
--When Bar() returns, if there is nothing aliased to the list foo,
then the list is destroyed

Is the my understanding correct?  Thank you again for taking the time
to review my question.


def Bar(foo=[]):
   foo.append("newb got a keyboard\n")
   return foo

if __name__ == "__main__":
   f = Bar()
   print f

C:\workspace\ProvingGrounds\src\Bill>python Bug.py
['newb got a keyboard\n', 'newb got a keyboard\n', 'newb got a
keyboard\n', 'newb got a keyboard\n']
-------------- next part --------------
A non-text attachment was scrubbed...
Name: example.py
Type: text/x-python
Size: 160 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20070221/79cdd609/attachment-0001.py 

More information about the Tutor mailing list