[Tutor] function local var problem :-((

Erik Price erikprice at mac.com
Sun Oct 5 17:13:03 EDT 2003


On Sunday, October 5, 2003, at 04:15  PM, mjekl at clix.pt wrote:

> The problem to me is that I think that the var printList is local and 
> that
> it is initialized every time the function is called. But results 
> contradict
> this assumption. So I tried to investigate the namespaces and found no
> references to var printList. I guess my investigation is bad (In shell 
> I
> issued dir() and dir(module1)
> and got nothing. Also tried to use:
>  from module1 import printHierarchy
> But didn't work either. Can someone please help me?

Very tricky, very subtle.  I found a relevant quote in Python Essential 
Reference 2nd Ed by David Beazley (p. 63):
<snip>
Default parameter values are always set to the objects that were 
supplied as values when the function was defined.  For example:

   a = 10
   def foo(x=a):
     print x

   a = 5			# reassign 'a'
   foo()			# prints '10' (default value not changed)

However, the use of mutable objects as default values can lead to 
unintended behavior:

   a = [10]
   def foo(x=a):
     print x
   a.append(20)
   foo()			# prints '[10, 20]'
</snip>

I follow this logic -- the variable is stored in the scope of the 
function definition itself (the scope where the function is defined).  
But that would strike me as being your module, and you said that the 
dir(your module) function didn't display the variable.  So I don't know.

Hopefully some guru can shed more light on that.


Erik




More information about the Tutor mailing list