grammar.md
1> **Источник:** https://python-all.ru/3.2/reference/grammar.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# 9. Полная спецификация грамматики89Это полная грамматика Python в том виде, в котором она читается генератором парсера и используется для разбора исходных файлов Python:1011```python12# Грамматика Python1314# Примечание: изменение грамматики, указанной в этом файле, скорее всего,15# потребует соответствующих изменений в модуле парсера16# (../Modules/parsermodule.c). Если вы не можете внести изменения в17# этот модуль самостоятельно, скоординируйте необходимые изменения18# с кем-то, кто может это сделать; спросите в python-dev о помощи. Fred19# Drake <fdrake@acm.org>, вероятно, будет там на связи.2021# ВАЖНО: Также необходимо выполнить все шаги, перечисленные в PEP 306,22# "Как изменить грамматику Python"2324# Начальные символы грамматики:25# single_input – это одиночный интерактивный оператор;26# file_input – это модуль или последовательность команд, прочитанная из входного файла;27# eval_input – это входные данные для функций eval() и input().28# NB: после compound_stmt в single_input следует дополнительный NEWLINE!29single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE30file_input: (NEWLINE | stmt)* ENDMARKER31eval_input: testlist NEWLINE* ENDMARKER3233decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE34decorators: decorator+35decorated: decorators (classdef | funcdef)36funcdef: 'def' NAME parameters ['->' test] ':' suite37parameters: '(' [typedargslist] ')'38typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [','39 ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]]40 | '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)41tfpdef: NAME [':' test]42varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [','43 ['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]]44 | '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)45vfpdef: NAME4647stmt: simple_stmt | compound_stmt48simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE49small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |50 import_stmt | global_stmt | nonlocal_stmt | assert_stmt)51expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) |52 ('=' (yield_expr|testlist_star_expr))*)53testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']54augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |55 '<<=' | '>>=' | '**=' | '//=')56# Для обычных присваиваний дополнительные ограничения, накладываемые интерпретатором57del_stmt: 'del' exprlist58pass_stmt: 'pass'59flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt60break_stmt: 'break'61continue_stmt: 'continue'62return_stmt: 'return' [testlist]63yield_stmt: yield_expr64raise_stmt: 'raise' [test ['from' test]]65import_stmt: import_name | import_from66import_name: 'import' dotted_as_names67# примечание ниже: ('.' | '...') необходимо, потому что '...' токенизируется как ELLIPSIS68import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+)69 'import' ('*' | '(' import_as_names ')' | import_as_names))70import_as_name: NAME ['as' NAME]71dotted_as_name: dotted_name ['as' NAME]72import_as_names: import_as_name (',' import_as_name)* [',']73dotted_as_names: dotted_as_name (',' dotted_as_name)*74dotted_name: NAME ('.' NAME)*75global_stmt: 'global' NAME (',' NAME)*76nonlocal_stmt: 'nonlocal' NAME (',' NAME)*77assert_stmt: 'assert' test [',' test]7879compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated80if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]81while_stmt: 'while' test ':' suite ['else' ':' suite]82for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]83try_stmt: ('try' ':' suite84 ((except_clause ':' suite)+85 ['else' ':' suite]86 ['finally' ':' suite] |87 'finally' ':' suite))88with_stmt: 'with' with_item (',' with_item)* ':' suite89with_item: test ['as' expr]90# NB: compile.c проверяет, что предложение except по умолчанию является последним.91except_clause: 'except' [test ['as' NAME]]92suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT9394test: or_test ['if' or_test 'else' test] | lambdef95test_nocond: or_test | lambdef_nocond96lambdef: 'lambda' [varargslist] ':' test97lambdef_nocond: 'lambda' [varargslist] ':' test_nocond98or_test: and_test ('or' and_test)*99and_test: not_test ('and' not_test)*100not_test: 'not' not_test | comparison101comparison: expr (comp_op expr)*102# <> на самом деле не является допустимым оператором сравнения в Python. Он здесь ради импорта __future__, описанного в PEP 401 (который действительно работает :-)).103# ради импорта __future__, описанного в PEP 401104comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'105star_expr: '*' expr106expr: xor_expr ('|' xor_expr)*107xor_expr: and_expr ('^' and_expr)*108and_expr: shift_expr ('&' shift_expr)*109shift_expr: arith_expr (('<<'|'>>') arith_expr)*110arith_expr: term (('+'|'-') term)*111term: factor (('*'|'/'|'%'|'//') factor)*112factor: ('+'|'-'|'~') factor | power113power: atom trailer* ['**' factor]114atom: ('(' [yield_expr|testlist_comp] ')' |115 '[' [testlist_comp] ']' |116 '{' [dictorsetmaker] '}' |117 NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')118testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )119trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME120subscriptlist: subscript (',' subscript)* [',']121subscript: test | [test] ':' [test] [sliceop]122sliceop: ':' [test]123exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']124testlist: test (',' test)* [',']125dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) |126 (test (comp_for | (',' test)* [','])) )127128classdef: 'class' NAME ['(' [arglist] ')'] ':' suite129130arglist: (argument ',')* (argument [',']131 |'*' test (',' argument)* [',' '**' test] 132 |'**' test)133# Причина, по которой ключевые слова являются узлами test, а не NAME, заключается в том, что использование NAME134# приводит к неоднозначности. ast.c проверяет, что это NAME.135argument: test [comp_for] | test '=' test # На самом деле [ключевое слово '='] тест136comp_iter: comp_for | comp_if137comp_for: 'for' exprlist 'in' or_test [comp_iter]138comp_if: 'if' test_nocond [comp_iter]139140# не используется в грамматике, но может появиться в "node", передаваемом от Parser к Compiler141encoding_decl: NAME142143yield_expr: 'yield' [testlist]144```145