[Python-3000] default argument surprises
Alex Martelli
aleaxit at gmail.com
Thu Aug 28 04:01:06 CEST 2008
On Wed, Aug 27, 2008 at 2:27 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
...
> Late binding default arguments would do some fairly bad things to nested
> functions such as preventing the use of class attributes when defining
They'd also be SERIOUSLY problematic wrt a VERY common issue -- one
that I had an excellent and Python-experienced colleague ask me about
just the other day as we were waiting for a meeting room to actually
get free for a meeting we were both at -- rephrasing and summarizing,
his problem was like:
for text, command in zip(labels, commands):
makebutton(text, lambda evt: command)
and the LAST command was being bound to all buttons (of course). With
current semantics I was able to give him the solution instantly (while
others were still streaming out of the conference room;-):
for text, command in zip(labels, commands):
makebutton(text, lambda evt, command=command: command)
If default args were late-bound, I'd have to offer exclusively the
more-complex "closure" approach:
def makecommand(command):
def doit(evt): return command()
return doit
for text, command in zip(labels, commands):
makebutton(text, makecommand(command))
which -- while I personally prefer it -- is _definitely_
heavier-weight. This issue does happen A LOT: I even saw it
highlighted in a popular text on Javascript (so, it's not even a
Python-only one;-).
Alex
More information about the Python-3000
mailing list