[Python-ideas] A conditional "for" statement -- postfix

spir denis.spir at free.fr
Fri Apr 24 12:07:05 CEST 2009


Le Thu, 23 Apr 2009 18:29:15 -0400,
"Michael S. Gilbert" <michael.s.gilbert at gmail.com> s'exprima ainsi:

> Hello, 
> 
> I've recently been working on some code where i am processing a 
> list, but excluding certain items.  The solution is to use a list 
> comprehension in the "for" statement.  An example is:
> 
>   for m in [n for n in range( 0 , 5 ) if n != 2]
> 
> Determining what's going on here isn't immediately obvious (i.e.
> what's this new variable n doing?).  It would be nice to have a more 
> streamlined syntax such as:
> 
>   for m in range( 0 , 5 ) with m != 2

Should be 'if' anyway; certainly not 'with', anyway.

> which is much cleaner and obvious. 

Actually, I see the syntactic issue differently. I applies to lambdas as well as list comps (that, in fact, also implicitely define unnamed funcs).
Often filtering or mapping expressions are straightforward operations on the items, so that the whole construct needed seems heavy redundance:
   [n for n in numbers if n!=2]
   filter(numbers, lambda n: n!=2)

What we would like to express is only the "operational" part of the expression:
   [numbers if !=2]
   filter(numbers, !=2)
This would be nice as well for a swtich-like statement:
   swith on x:
      case == 0: ...
      case < 0:  ...
      case > 0:  ...
      else:      ;-)

But this is (imo elegant) postfix syntax that allows omitting parameters using an implicit value stack, but does not fit in python, I guess.
   def half: return 2 /
   def square: return dup *
   def sum: return +
The price to pay is difficult stack juggling as soon as operations are not trivial.

What I would certainly like is restricting the field of anonymous func expression (in both lambdas and list comps) to these trivial cases -- so that we could then omit parameters/items using postfix syntax. Otherwise use a defined func wich implicit parameter is the item.
Of course the drawback is that expressions of very low level of complication would have to be defined in a func:
   def hasValidValue(result):
      return result.value is not None
   validResults = [results if hasValidValue]
But we may allow attribute syntax:
   noneResults = [results if .value]

> Best Regards,
> Mike


Denis
------
la vita e estrany



More information about the Python-ideas mailing list