Somthing strange with list as default argument

J

Julien Sagnard

A

Alex Martelli

Julien Sagnard said:
Hi all,

When passing a list as default argument for a function, only one list is
created for all calls.
Right.

I'm not found any reference of this. Is it a bug ?

No, you just didn't look in the right places, for example in the
Tutorial which is the recommended first reading for new Python users.

Under 4.7.1 the Tutorial says:

"""
Important warning: The default value is evaluated only once. This makes
a difference when the default is a mutable object such as a list,
dictionary, or instances of most classes.
"""

The 'Important warning' is in bold, too...


Alex
 
D

Duncan Booth

S

Sam Holden

Hi all,

When passing a list as default argument for a function, only one list is
created for all calls.
exemple:
... a.append("x")
... print a
...
f() ['x']
f() ['x', 'x']
f() ['x', 'x', 'x']
f() ['x', 'x', 'x', 'x']

I'm not found any reference of this. Is it a bug ?

http://docs.python.org/tut/node6.html#SECTION006710000000000000000
(see the bold "important warning")

http://docs.python.org/ref/function.html
(see the paragraph with the bold text)

http://www.python.org/doc/faq/general.html
#why-are-default-values-shared-between-objects
(see the whole of 1.4.21 - link should be all one string with no new line...)

The tutorial, the reference docs, and the FAQ all mention this. There
isn't anywhere left to reference it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,206
Messages
2,571,069
Members
47,678
Latest member
Aniruddha Das

Latest Threads

Top