python3: 'where' keyword

Nick Coghlan ncoghlan at iinet.net.au
Sat Jan 8 23:43:50 EST 2005


Bengt Richter wrote:
> On Sat, 08 Jan 2005 16:42:16 +1000, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> And, is the whole thing after the '=' an expression? E.g.,
> 
>   x = ( foo(x) where:
>          x = math.pi/4.0
>       ) where:
>          def foo(x): print 'just for illustration', x
> 
> or is this legal?
> 
>   for y in ([foo(x) for x in bar] where:
>                  bar = xrange(5)
>             ): baz(y) where:
>                 def baz(arg): return arg*2
> 
> Not trying to sabotage the idea, really, just looking for clarification ;-)

Actually, I was conceiving this as an addition to the grammar for the relevant 
'simple statements', rather than to the grammar for expressions. Using the 
assignment statement as the ongoing example:

Current:
   assignment_stmt ::= (target_list "=")+ expression_list
   augmented_assignment_stmt ::=	target augop expression_list

New:
   assignment_stmt ::= (target_list "=")+ expression_list [where_clause]
   augmented_assignment_stmt ::=	target augop expression_list [where_clause]
   where_clause ::= "where" ":" suite

So the expressions in existing compound statements (for, while, if, elif) would 
be out of luck. You could conceivably add the 'where' clause to the end of those 
as well, to give statement local variables that apply to the whole compound 
statement:

   for y in [foo(x) for x in bar]:
     baz(y)
   where:
     meaningful_name = xrange(5)
     def baz(arg):
       return arg * 2

This would only be appropriate for short loops - for long loops, the 'where' 
clause gets *too* hidden.

Keeping the grammar simple might favour making the addition higher in the parse 
tree:

Current:
   statement ::=	stmt_list NEWLINE | compound_stmt

New:
   statement ::=	(stmt_list NEWLINE | compound_stmt) [where_clause]
   where_clause ::= "where" ":" suite

However, doing it that way allows nonsense like this:
   pass where:
     print "This is just plain silly!"

That would be something to be thrashed out in a PEP, though.

The name 'statement local variables' also gave me an idea for a rough 
implementatation strategy.

   <stmt> where:
     <suite>

would be equivalent to:

   def stmt_with_locals():
     <suite>
     <stmt>
   stmt_with_locals()

For the assignment versions, the behaviour would be:

   def assignment_with_locals():
     <suite>
     <stmt>
     return <name>
   <name> = assignment_with_locals()

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list