block/lambda

Terry Reedy tjreedy at udel.edu
Tue Jul 29 15:11:53 EDT 2008



iu2 wrote:
> On Jul 29, 9:36 am, Duncan Booth <duncan.bo... at invalid.invalid> wrote:

>> Your example becomes:
>>
>>>>> def dotimes(n, callable):
>>         for i in range(n): callable(i)
>>
>>>>> def block(i):
>>         for j in range(i):
>>                 print j,
>>         print
>>
>>>>> dotimes(5, block)
>> 0
>> 0 1
>> 0 1 2
>> 0 1 2 3
>>
>> The only thing you asked for that this doesn't do is make 'block'
>> anonymous, but actually that is a good thing.

> 
> Ok, I've got 2 questions about it:
> 
> 1. Can you please explain why it is a good thing?

All functions defined with lambda expressions get the pseudoname 
'<lambda>'.  All functions defined with def get the name you give it, 
which is typically unique within some scope.  The representation of a 
function, whether intentionally printed or printed as part of a 
traceback, is more meaningful with a specific name than a general name.


> 2. Will it be possible in Python 3.0 to do the following:
> 
>>>> def dotimes(n, callable):
>         for i in range(n): callable()
> 
>>>> def block():
>         nonlocal i
>         for j in range(i):
>                 print j,
>         print

If you indent block so it is a nested function, yes.  But the nonlocal 
declaration is not needed unless you rebind 'i' from within the nested 
function, which block does not do.

tjr




More information about the Python-list mailing list