Bug?? reusing objects
Peter Hansen
peter at engcorp.com
Sun May 26 01:08:08 EDT 2002
Damian Menscher wrote:
>
> The following test program demonstrates what I believe is a bug:
> -------------------------------------------------------------
> #!/tmp/Python-2.2.1/python
>
> class foobar:
> def __init__(self, string=[]):
> self.data = string
[snip example using default parameter]
> -------------------------------------------------------------
> If this is expected behavior, could someone please explain it?
> Otherwise, I'll be happy to file a bug report.
Not a bug. Default parameters are evaluated once at function
definition time, and used repeatedly thereafter. There is
only one empty list there, no matter how many times you create
a new object. Works for simple functions too:
>>> def fun(test=[]):
... test.append('x')
... print test
...
>>> fun()
['x']
>>> fun()
['x', 'x']
I believe this is a FAQ...
-Peter
More information about the Python-list
mailing list