[Python-ideas] 'where' statement in Python?

Sergio Davis sergdavis at gmail.com
Tue Jul 20 03:45:27 CEST 2010

Dear members of the python-ideas mailing list,

I'm not quite sure if this is the right place to ask for feedback about the
idea, I apologize if this is not the case.

I'm considering the following extension to Python's grammar: adding the
'where' keyword, which would work as follows:

where_expr : expr 'where' NAME '=' expr

The idea is to be able to write something like:

a = (z**2+5) where z=2

being equivalent to (current Python syntax):

a = (lambda z: z**2+5)(z=2)

I thinkg this would be especially powerful in cases where the variable to be
substituted ('z' in the example) comes in turn from a complicated
expression, which makes it confusing to "embed" it in the main expression
(the body of the 'lambda'), or in cases where the substitution must be
performed more than once, and it may be more efficient to evaluate 'z' once.
A more complicated example:

vtype = decl[par_pos+1:FindMatching(par_pos, decl)].strip() where

equivalent to (current Python syntax):

vtype = (lambda par_pos:

Extending this syntax to several assignments after the 'where' keyword could
be implemented as:

where_expr: expr 'where' NAME '=' expr (',' NAME '=' expr )*

or (which I think may be more "pythonic"):

where_expr: expr 'where' NAME (',' NAME)* '=' expr (',' expr)*

as it mimics the same syntax for unpacking tuples.

I would appreciate any feedback on the idea, especially if it has some
obvious flaw or if it's redundant (meaning there is a clearer way of doing
this 'trick' which I don't know about).

best regards,

   Sergio Davis

Sergio Davis Irarrázabal
Grupo de NanoMateriales, Universidad de Chile
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20100719/607618ab/attachment.html>

More information about the Python-ideas mailing list