[Tutor] function local var problem :-((

Lloyd Kvam pythontutor at venix.com
Sun Oct 5 16:36:37 EDT 2003


This is a common pitfall in Python.  The initial empty list is created
ONCE, when the function is defined.  It is NOT created each time
the function is called and that argument is not specified.

Since lists are mutable, the default list changes as it is used.  The most
common solution is usually:
def printHierarchy(objecto, printList=None):
	if printList is None:
		printList = []

None is immutable so the default value can't be changed.  Now we create
a new empty list every time no list is supplied.


mjekl at clix.pt wrote:

> 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
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582




More information about the Tutor mailing list