Beginner question - How to effectively pass a large list

J.R. j.r.gao at motorola.com
Tue Dec 16 22:43:57 EST 2003


> As penance for having failed to do this,
> I assign a more mysterious problem to you:
>
>    def f(d=[]):
>       d.append(0)
>       print d
>    f()
>    f()
>
> Explain results.  When is d bound?
>

I found that the "problem" showed above is caused by the python principle
"everything
is object".

Here the function "f" is an object as well, the object function f is created
once this function is defined. And there is tuple attribute(func_defaults)
inside
function object to record the default arguments.
>>> def f(d=[]):
        print id(d)
        d.append(0)
        print d
>>> f.func_defaults
([],)
>>> id(f.func_defaults[0])
11279792
>>> f()
11279792
[0]
>>> f()
11279792
[0, 0]
>>> f([1])
11279952
[1, 0]

1. There is no value passed to the default argument
The name "d" is bound to the first element of the f.func_defaults. Since the
function "f" is an
object, which will be kept alive as long as there is name (current is "f")
refered to it, the
list in the func_defaults shall be accumulated by each invoking.

2. There is a value passed to the default argument
The name "d" will be bound to the passed object, it's proven from the
different identity showd above.

I think we could eliminate such accumulation effect by changing the function
as follow:
>>> def f(d=[]):
        d = d+[0]
        print d

J.R.






More information about the Python-list mailing list