On 1/25/2011 3:41 PM, Karim wrote:
Hello All,
Just to share on rageous bug I encounter where 2 lists which "should"
to be different (same id) because hold by different instances of the
same class are not in fact DIFFERENT, see below:
>>> class Device():
... def __init__(self, parameters=[]):
... self.parameters = parameters
... def param(self):
... print(id(self.parameters))
...
>>> a=Device()
>>> b=Device()
>>> a.param()
140559202956568
>>> b.param()
140559202956568
This is not a bug. It is intentional behavior which is documented in the
Python Language Reference.
Under 7.6 Function definitions you will find:
*Default parameter values are evaluated when the function definition is
executed.* This means that the expression is evaluated once, when the
function is defined, and that that same "pre-computed" value is used for
each call. This is especially important to understand when a default
parameter is a mutable object, such as a list or a dictionary: if the
function modifies the object (e.g. by appending an item to a list), the
default value is in effect modified. This is generally not what was
intended. A way around this is to use None as the default, and
explicitly test for it in the body of the function, e.g.:
--
Bob Gailer
919-636-4239
Chapel Hill NC
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor