[Python-ideas] Statements vs Expressions... why?

Terry Reedy tjreedy at udel.edu
Fri Sep 12 02:24:03 CEST 2008


Cliff Wells wrote:

>> If you have a link with real live
>> examples - in particular, showing how you can use for loops to replace
>> lcs and similar things, please provide it.
> 
>>From an earlier example I posted:
> 
> dispatch = {
>     '1': lambda x: (
>            for i in range(x): 
>                if not x % 2:
>                    yield 0
>                else:
>                    yield 1 
>          ),
> 
>     '2': lambda x: (
>             for i in range(x):
>                 yield i  
>          )
> }
> 
> for i in dispatch[val](1):
>     print i

To me, this is the most (perhaps only ;-) readable such example.  But it 
is unnecessary.  Even without metaclasses, as someone else suggested 
(and thank you for the idea), the following works today, and is even 
more readable to me.

class disclass(): # 3.0
   def f1(x):
     for i in range(x):
       if not x % 2:
         yield 0
       else:
         yield 1
   def f2(x):
     for i in range(x):
       yield i

dispatch = disclass.__dict__

val = '1'
for i in dispatch['f'+val](2):
     print(i)
for i in dispatch['f'+val](3):
     print(i)

val = '2'
for i in dispatch['f'+val](4):
     print(i)

 >>>
0
0
1
1
1
0
1
2
3

In 3.0, a class decorator could, I believe, both replace the class with 
its dict, and strip the leading 'f' from the 'fn' keys.  So there is 
another 'need' for generalized lambda that isn't.

Terry Jan Reedy




More information about the Python-ideas mailing list