Skip to content

Commit 906b345

Browse files
authored
[3.10] gh-94949: Disallow parsing parenthesised ctx mgr with old feature_version (GH-94950) (#94990)
(cherry picked from commit 0daba82) Co-authored-by: Shantanu <[email protected]>
1 parent 96e1516 commit 906b345

File tree

4 files changed

+11
-2
lines changed

4 files changed

+11
-2
lines changed

Grammar/python.gram

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ for_stmt[stmt_ty]:
192192
with_stmt[stmt_ty]:
193193
| invalid_with_stmt_indent
194194
| 'with' '(' a[asdl_withitem_seq*]=','.with_item+ ','? ')' ':' b=block {
195-
_PyAST_With(a, b, NULL, EXTRA) }
195+
CHECK_VERSION(stmt_ty, 9, "Parenthesized context managers are", _PyAST_With(a, b, NULL, EXTRA)) }
196196
| 'with' a[asdl_withitem_seq*]=','.with_item+ ':' tc=[TYPE_COMMENT] b=block {
197197
_PyAST_With(a, b, NEW_TYPE_COMMENT(p, tc), EXTRA) }
198198
| ASYNC 'with' '(' a[asdl_withitem_seq*]=','.with_item+ ','? ')' ':' b=block {

Lib/test/test_ast.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,14 @@ def test_ast_asdl_signature(self):
686686
expressions[0] = f"expr = {ast.expr.__subclasses__()[0].__doc__}"
687687
self.assertCountEqual(ast.expr.__doc__.split("\n"), expressions)
688688

689+
def test_parenthesized_with_feature_version(self):
690+
ast.parse('with (CtxManager() as example): ...', feature_version=(3, 10))
691+
# While advertised as a feature in Python 3.10, this was allowed starting 3.9
692+
ast.parse('with (CtxManager() as example): ...', feature_version=(3, 9))
693+
with self.assertRaises(SyntaxError):
694+
ast.parse('with (CtxManager() as example): ...', feature_version=(3, 8))
695+
ast.parse('with CtxManager() as example: ...', feature_version=(3, 8))
696+
689697
def test_issue40614_feature_version(self):
690698
ast.parse('f"{x=}"', feature_version=(3, 8))
691699
with self.assertRaises(SyntaxError):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:func:`ast.parse` will no longer parse parenthesized context managers when passed ``feature_version`` less than ``(3, 9)``. Patch by Shantanu Jain.

Parser/parser.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4657,7 +4657,7 @@ with_stmt_rule(Parser *p)
46574657
UNUSED(_end_lineno); // Only used by EXTRA macro
46584658
int _end_col_offset = _token->end_col_offset;
46594659
UNUSED(_end_col_offset); // Only used by EXTRA macro
4660-
_res = _PyAST_With ( a , b , NULL , EXTRA );
4660+
_res = CHECK_VERSION ( stmt_ty , 9 , "Parenthesized context managers are" , _PyAST_With ( a , b , NULL , EXTRA ) );
46614661
if (_res == NULL && PyErr_Occurred()) {
46624662
p->error_indicator = 1;
46634663
p->level--;

0 commit comments

Comments
 (0)