Grammar
Python's grammar is a PEG (Parsing Expression Grammar) since 3.9.
The canonical definition lives in Grammar/python.gram. This page
indexes every non-terminal, gives the entry points, and explains
the lookahead conventions.
Entry points
| Mode | Start symbol | Used by |
|---|---|---|
exec / file | file | pythonrun.RunSimpleString, .py files. |
eval | eval | parser.ModeEval, eval(). |
single / REPL | interactive | parser.ModeSingle, gopy -c. |
| Function type | func_type | typing.get_type_hints. |
The start symbol consumes input until ENDMARKER. Anything left
over is a SyntaxError.
Top-level structure
file: [statements] ENDMARKER
interactive: statement_newline
eval: expressions [NEWLINE]* ENDMARKER
func_type: '(' [type_expressions] ')' '->' expression [NEWLINE]* ENDMARKER
Statement classes
| Non-terminal | Covers |
|---|---|
statements | One or more statement. |
statement | A compound or a simple-statement sequence. |
statement_newline | Statement followed by NEWLINE (interactive). |
simple_stmts | ;-separated simple_stmts, terminated by NEWLINE. |
simple_stmt | One of the simple statements (see below). |
compound_stmt | if, while, for, try, with, match, function_def, class_def, async_stmt. |
Simple statement productions
| Production | Syntax |
|---|---|
assignment | Targets, augmented, annotated. |
type_alias | type Name = expression |
star_expressions | Bare expression statement (top-level). |
return_stmt | 'return' [star_expressions] |
import_stmt | import_name or import_from. |
raise_stmt | 'raise' [expression ['from' expression]] |
pass_stmt | 'pass' |
del_stmt | 'del' del_targets |
yield_stmt | yield_expr |
assert_stmt | 'assert' expression [',' expression] |
break_stmt | 'break' |
continue_stmt | 'continue' |
global_stmt | 'global' NAME (',' NAME)* |
nonlocal_stmt | 'nonlocal' NAME (',' NAME)* |
Compound statement productions
| Production | Heads |
|---|---|
function_def | def, async def, with @decorator stack. |
class_def | class, with decorators and PEP 695 type params. |
if_stmt | if, elif, else. |
while_stmt | while, optional else. |
for_stmt | for / async for, optional else. |
with_stmt | with / async with, parenthesised items. |
try_stmt | try with any of except, except*, else, finally. |
match_stmt | match with one or more case clauses. |
async_stmt | async def, async for, async with. |