I am new to python. I have a few questions coming from an armature!

Peter Otten __peter__ at web.de
Thu Aug 18 06:12:42 EDT 2016


Steven D'Aprano wrote:

> On Thursday 18 August 2016 06:25, Terry Reedy wrote:

> Sure. But since the behaviour of def functions and lambda functions are
> identical, writing a named def won't solve that problem.
> 
> 
>>          for section_name, line_number in text.parser.toc:
>>              def goto(line=line_number):
>>                  text.yview(line)
>>              drop.add_command(label=section_name, command=goto)
>> 
>> To me, this is much better and I intend to commit it.  Thank you for
>> prodding me to think through how bad the lambda form can be and to
>> rewrite the loop so I don't cringe reading it.
> 
> The use of a named function here adds next to nothing. Instead of some
> number of anonymous functions called "<lambda>", you have an equal number
> of functions all named "goto". 

There may be other lambdas that do something completely different. For 
someone not familiar with the code in question a name gives a good hint were 
to look.

> There's no easy way to distinguish them,
> and likely no real need to distinguish them -- they are simple enough that
> you can be almost certain that they are correct just from reading the
> code. So I don't see any benefit over this:
> 
>          for section_name, line_number in text.parser.toc:
>              drop.add_command(label=section_name, command=lambda
>                               line=line_number: text.yview(line))
> 
> except that it is easier to fit in 79 columns :-)

There is also

>>> functools.partial(text.yview, line_number)
functools.partial(<bound method Text.yview of <tkinter.Text object at 
0x7f1539dfd1d0>>, 42)

The repr() is unwieldy, but the underlying function and its arguments are 
there.




More information about the Python-list mailing list