Default list parameter issue

Olivier Boudeville olivier.boudevilleNOSPAM at online.fr
Fri Aug 6 12:35:04 EDT 2004


Hi all,

it must be a very stupid question but I cannot find out the explanation 
for my code's behaviour, so any help would really be appreciated.


My purpose was, simply put, to have a tree-like data structure, thanks 
to the following (simplified to track the issue) Node class :

class Node:
	
	
	def __init__( self, newContent = None  ) :
		"""Creates an empty node with no child node."""
		self.content  = newContent
		self.children = []	

	def __repr__( self ):
		"""Returns a textual representation of this node's state."""
		res = "Node has "
		if self.content:
			res += "content (%s)" % ( self.content, )
		else:
			res += "no content"
		res += " and it has "	
		if self.children:
			res += "%s child(ren) : <%s>" % ( len( self.children ),self.children  )
		else:
			res += "no child."
			
		return res
	
	def addChild( self, aChild ):
		"""Adds a child to current node."""	
		self.children.append( aChild )



I test the class simply thanks to :
a=Node()
b=Node()
print a
print b
a.addChild( b )
print a
print b

and it returns, as expected :

 >>> a=Node()
 >>> b=Node()
 >>> a
Node has no content and it has no child.
 >>> b
Node has no content and it has no child.
 >>> a.addChild( b )
 >>> a
Node has no content and it has 1 child(ren) : <[Node has no content and 
it has no child.]>
 >>> b
Node has no content and it has no child.

That is ok. But if I swap the previous __init__ method with my first 
version :

	def __init__( self, newContent = None, newChildren = [] ) :
		"""Creates an empty node with no child node."""
		self.content  = newContent
		self.children = newChildren

and I apply the same test, I got (output not edited) :

 >>> a=Node()
 >>> b=Node()
 >>> a
Node has no content and it has no child.
 >>> b
Node has no content and it has no child.
 >>> a.addChild( b)
 >>> a
Node has no content and it has 1 child(ren) : <[Node has no content and 
it has 1 child(ren) : <[...]>]>
 >>> b
Node has no content and it has 1 child(ren) : <[Node has no content and 
it has 1 child(ren) : <[...]>]>
 >>>

I do not understand why using an empty list as default parameter results 
  in such a different behaviour.

Thanks in advance for any hint,
kind regards,

Olivier.


PS : tested with python 2.2.1 and 2.3.3. The test should be relevant since :

 > diff ok.py   ko.py
2,4c2,4
<
<
<       def __init__( self, newContent = None  ) :
---
 >
 >
 >       def __init__( self, newContent = None, newChildren = [] ) :
7c7
<               self.children = []
---
 >               self.children = newChildren

Olivier.




More information about the Python-list mailing list