strange list behavior

Sean Blakey sblakey at freei.net
Tue Jun 6 15:13:05 EDT 2000


On Tue, Jun 06, 2000 at 06:50:16PM +0000, Stefan Seefeld wrote:
> I'v run into a strange problem with lists. I'm not sure
> at all where the problem is so I'll provide some context:
> 
[snip]
> class Visitor:
>     def visitDeclarator(self, node):
>         name = self.scope()
>         name.append(node.identifier())
>         self.__result_declarator = AST.Declarator(name)
>     def visitModule(self, node):
>         name = self.scope()
>         name.append(node.identifier())
>         module = AST.Module(name)
> #...
> 
> what I *though* was happening is that I created temporary variables 'name'
> in the respective scopes of all the visitSomething methods and then hand over
> the objects to the newly created Node types (Module, Declarator, etc.)
> However, what I *observe* is that even though a Module is initialized with
> name : ['foo', 'bar']
> it may end up being
> name : ['foo', 'baz']
> i.e. it seems the list is not properly released but instead modified from the outside. 
> printing out 'id(name)' reveals indeed that the various temporary 'name' objects 
> in the Visitor class have all the same id, i.e. they are the same object. Given
> that the AST nodes are created with the list copied by reference, not by value,
> I should not wonder that the value changes. Is this a fault of GC ?
> 
> Could anybody explain what's going on here and how I get the behavior I want ?
> Thanks a lot !
> 
> Stefan
> 
> _______________________________________________________              
>               
> Stefan Seefeld
> Departement de Physique
> Universite de Montreal
> email: seefelds at magellan.umontreal.ca
> 
> _______________________________________________________
> 
>       ...ich hab' noch einen Koffer in Berlin...
> -- 
> http://www.python.org/mailman/listinfo/python-list

It looks like what is happening is that your self.scope() method is
returning a reference to an existing list instead of a new list.  You do
not provide any code for your scope() method so I cannot verify this,
but I would guess that you are doing something like this:
    def scope(self, default_scope=[]):
	# manipulate default_scope here
	return default_scope

When you use a mutable object as the default argument of a function or
method in python, that object is only initialized once.  Each call to
self.scope() will return a reference to the same list.
    -Sean
-- 
Sean Blakey, sblakey at freei.com
Software Developer, FreeInternet.com
(253)796-6500x1025
It is easier to change the specification to fit the program than vice versa.




More information about the Python-list mailing list