>>> def f(l, r = []):
for itm in l:
r.append(itm)
print r
>>> a = [1,2,3]
>>> f(a)
[1, 2, 3]
>>> f(a)
[1, 2, 3, 1, 2, 3]
>>> f(a)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
I know the function is quite artificial, but it's for illustration only.
Why is "r" not being reset to the empty list on subsequent calls? It
seems like it should be reinitialized when not explicitly provided.
Thanks in advance.
Mike
from http://docs.python.org/ref/function.html :
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.
Mike
This comes up so often that I wonder whether Python should issue a warning
when it sees [] or {} as a default argument.
What do people think? A misuse or good use of warnings?
--
Steven.
<http://www.python.org/doc/faq/general/#why-are-default-values-shared-be
tween-objects>
Alex
I wonder if it is a check done by Pylint or PyChecker?
- Paddy.
I think Python should reevaluate the default values.
--
mvh Björn
That would break code that relies on the current behaviour. That makes it
a "maybe" for Python 3.0, and an absolute "NO!!!" for Python 2.x.
--
Steven.
If you hope to get any change in Python 3.0, your PEP had better be in
before the end of April -- that's the 3.0 deadline for PEPs.
Alex
It is a check done by pylint
Tim
>
> - Paddy.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>