[Python-ideas] 'where' statement in Python?
Jack Diederich
jackdied at gmail.com
Tue Jul 20 03:52:47 CEST 2010
On Mon, Jul 19, 2010 at 9:45 PM, Sergio Davis <sergdavis at gmail.com> wrote:
> 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
> par_pos=decl.find('(')
>
> equivalent to (current Python syntax):
>
> vtype = (lambda par_pos:
> decl[par_pos+1:FindMatching(par_pos,decl)].strip())(par_pos=decl.find('('))
>
> 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).
>
I think the "trick" to making it readable is putting the assignment first.
par_pos = decl.find('(')
vtype = decl[par_pos+1:FindMatching(par_pos, decl)].strip()
versus:
vtype = decl[par_pos+1:FindMatching(par_pos, decl)].strip() where
par_pos=decl.find('(')
-Jack
More information about the Python-ideas
mailing list