Python Grammar: with_stmt

In the full grammar specification of python with instruction is defined as:

 with_stmt: 'with' with_item (',' with_item)* ':' suite with_item: test ['as' expr] 

Where expr :

 expr: xor_expr ('|' xor_expr)* xor_expr: and_expr ('^' and_expr)* and_expr: shift_expr ('&' shift_expr)* 

Why with_item contain an expr rule instead of a plain name ?

This is valid python code:

 with open('/dev/null') as f: pass 

According to the grammar, is this code also valid?

 with open('/dev/null') as x^y|z: pass 
+6
source share
1 answer
 with open('/dev/null') as x^y|z: pass 

Yes, this code is valid according to the grammar! Otherwise, you will receive a parsing error ("invalid syntax"). The native parser is good with this syntax, it is another part of the compiler that checks that such an expression is not allowed on the left side (because as semantically equivalent to the destination). The reason the grammar allows expr here, and not just NAME is because you can get any l as value:

 with open('/dev/null') as some.thing with open('/dev/null') as some[thing] 

but there is no separate rule for lvalues, for example. assignments use testlist on the left, which is even wider than expr .

+6
source

Source: https://habr.com/ru/post/976848/


All Articles