I was going through the python grammer specification and find the following statement,
for_stmt: | 'for' star_targets 'in' ~ star_expressions ':' [TYPE_COMMENT] block [else_block]
What does ~
means in this grammar rule?. The other symbols used in the grammer(like &
, !
, |
) are already documented but not ~
.
The notation is a mixture of
EBNF
andPEG
. In particular,&
followed by a symbol, token or parenthesized group indicates a positive lookahead (i.e., is required to match but not consumed), while!
indicates a negative lookahead (i.e., is required not to match). We use the|
separator to mean PEG’s “ordered choice” (written as/
in traditional PEG grammars)
.
/= Division Assignment Divides the variable by a value and assigns the result to that variable.
The Python print() function takes in python data such as ints and strings, and prints those values to standard out. To say that standard out is "text" here means a series of lines, where each line is a series of chars with a '\n' newline char marking the end of each line. Standard out is relatively simple.
What is the Tilde ~ in Python? Python's Tilde ~n operator is the bitwise negation operator: it takes the number n as binary number and “flips” all bits 0 to 1 and 1 to 0 to obtain the complement binary number. For example, the tilde operation ~1 becomes 0 and ~0 becomes 1 and ~101 becomes 010 .
It's documented in PEP 617 under Grammar Expressions:
~
Commit to the current alternative, even if it fails to parse.
rule_name: '(' ~ some_rule ')' | some_alt
In this example, if a left parenthesis is parsed, then the other alternative won’t be considered, even if some_rule or ‘)’ fail to be parsed.
The ~
basically indicates that once you reach it, you're locked into the particular rule and cannot move onto the next rule if the parse fails.
PEP 617 mentions earlier that | some_alt
can be written in the next line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With