[Tutor] function local var problem :-((

Gregor Lingl glingl at aon.at
Sun Oct 5 16:49:29 EDT 2003


Hi Miguel,

you ran into a well known pitfall, which you can observe
in a very simple case here:

 >>> def test(l=[]):
    l.append(1)
    print l
 
 >>> test()
[1]
 >>> for i in range(3):
    test()
  
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]

it occurs if you use an object as default argument
which is *mutable*, for instance a list.

then l points to an object, which is created
only when the function is *defined*, notwhen it
is called.

As long as there is no new assignment to l, this object
is retained  and can be changed if it's mutable.
This is done in your  example  and in the one above.
Every new function call uses the actual state of l.

Remark: As far as I see you could solve your problem
by deleting the defaultargument in the definition and then
call

 >>> printHierarchy(oSub2, [])

Hope that helps,
Gregor


mjekl at clix.pt schrieb:

>Hi,
>
>I'm new here and with programming. I've been learning on my own and cannot
>understand what happens with this function I created.
>
>The function is in it's own module that I import into shell.
>
>###### module1.py ######
>
>def printHierarchy(objecto, printList=[]):
>   """Prints a class hierarchy given an object.
>      Works only with single inheritance hierarchies."""
>
>   if objecto.__class__.__bases__:
>      printList.append(objecto.__class__.__name__)
>      recurObjecto = objecto.__class__.__bases__[0]()
>      return printHierarchy(recurObjecto, printList)
>   else:
>      printList.append(objecto.__class__.__name__)
>
>      if not objecto.__class__.__bases__:
>	 i = 0
>	 for klass in printList:
>	    print i * ' ' + klass
>	    i += 1
>      else:
>	 return printList
>
>####################
>
>in shell I created a hierarchy of three classes:
>class Sup; class Sub1(Sup); class Sub2(Sub1)
>
>Then:
>  
>
>>>>oSub2 = Sub2()
>>>>printHierarchy(oSub2)
>>>>        
>>>>
>Sup
>   Sub1
>      Sub2
>  
>
>
>The problem is that if I call the function again I get:
>  
>
>>>>printHierarchy(oSub2)
>>>>        
>>>>
>Sup
>   Sub1
>      Sub2
>	 Sup
>	    Sub1
>	       Sub2
>  
>
>
>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?
>
>Python 2.2 winXP
>
>Txs,
>Miguel
>
>Clix Rapidix - Aumente até 6X a velocidade da sua Internet
>Adira em http://acesso.clix.pt e comece logo a navegar
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>




More information about the Tutor mailing list