473,387 Members | 1,745 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Default list parameter issue

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.

Jul 18 '05 #1
2 1758
Olivier Boudeville wrote:
I do not understand why using an empty list as default parameter results
in such a different behaviour.


You are not alone.

http://www.python.org/doc/faq/genera...etween-objects

Peter
Jul 18 '05 #2
Oh, thanks a lot Peter, I did not know about it and was totally stuck.

IMHO, this 'feature' is counter-intuitive. Maybe it allows to write in
some cases simplier or more efficient functions, but there are enough
traps not to add more of them, with this kind of side-effects.

I believed, with filter, list comprehension and so on, that python was
making some steps towards 'functional programming' and declarative
languages (sorry if the translations are not accurate). It would have
led to more robust code. It is certainly not that way that recursive
functions will be easy to write and understand (but it is just my
opinion) !

I do not find/wish this behaviour is 'pythonic', but of course it is a
matter of taste.

Thanks again nevertheless, it helped me a lot !

Olivier.
Peter Otten wrote:
Olivier Boudeville wrote:

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

You are not alone.

http://www.python.org/doc/faq/genera...etween-objects

Peter


Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
by: Alex Panayotopoulos | last post by:
Hello all, Maybe I'm being foolish, but I just don't understand why the following code behaves as it does: - = - = - = - class listHolder: def __init__( self, myList= ): self.myList =...
49
by: Mark Hahn | last post by:
As we are addressing the "warts" in Python to be fixed in Prothon, we have come upon the mutable default parameter problem. For those unfamiliar with the problem, it can be seen in this Prothon...
10
by: Ernst Murnleitner | last post by:
Dear C++ programmers, I have 2 classes A and B with virtual functions virtual long A::Save(); virtual long B::Save(bool b = true); Now, if I have a Pointer A * which points to a B Object:
18
by: Dan Cernat | last post by:
Hi there, A few threads I had a little chat about default values. I am starting this thread because I want to hear more opinions about the default values of function parameters. Some say they...
18
by: Matt | last post by:
I try to compare the default constructor in Java and C++. In C++, a default constructor has one of the two meansings 1) a constructor has ZERO parameter Student() { //etc... } 2) a...
2
by: Vic Y | last post by:
Hi, I am trying to call a user defined function(UDF) from a stored proc, using a default parameter in the called UDF (e.g. @bid_price_type int = 0 ). However the calling stored proc complains...
9
by: gamehack | last post by:
Hello all again, Sorry for troubling you with my problems. I've tried to implement simple double linked lists, here's my structure: struct DResult { double val; char* title; struct DResult*...
11
by: Matthias Pfeifer | last post by:
Hi there, I am trying to declare a function that takes a std::list<parameter. I want this function to have an empty list as a default parameter. It's a template function also. Currently i am...
1
by: abedford | last post by:
Hi, I would like to add a default parameter to a COM function. I defined it in the IDL file like this: HRESULT GetName( BSTR id1 , BSTR id2 , ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.