[Python-3000] default argument surprises

Sam Bishop samuel.j.bishop at gmail.com
Wed Aug 27 05:21:53 CEST 2008


Hi, all.

I know that Python 3.0 is quite a ways along, but I'd like to make two
small suggestions with regards to how the language works.  (I would
have spoken up earlier, except that I'm very new to Python.)

I've talked to a few of my co-workers who are also new to Python, and
we've all been surprised at the way code like this behaves:

:def process(L=[]):
:    # 'x' always needs processed...
:    L += ['x']
:    print L
:
:process()  # prints "['x']"
:process()  # prints "['x', 'x']"!

We've been able to figure out what's happening, but it seems counter-intuitive.

If Python were changed so that default-argument, rvalue objects were
recreated each time a function is invoked, I think that it would be
intuitive (and efficient) if the object were only created when
necessary.  Here's (approximately) another code snippet I've seen
recently:

:def determine_default():
:    print "Why is this code executing?"
:    return 1
:
:def fun(arg=determine_default()):
:    pass
:
:fun("value")

Thanks,
Sam


More information about the Python-3000 mailing list