Skip to content

ast.parse() believes valid context manager py38 syntax to be invalid when feature_version=(3, 8) is passed #115881

Closed
@AlexWaygood

Description

@AlexWaygood

Bug report

Bug description:

The following code is completely valid on Python 3.8:

from contextlib import nullcontext

with (
    nullcontext() if bool() else nullcontext()
):
    pass

However, following 0daba82 (which was backported to Python 3.11 and Python 3.10), ast.parse() incorrectly throws an error if you try to parse this code with feature_version=(3, 8):

% python                                                                                                                         
Python 3.10.6 (main, Feb 24 2024, 10:35:05) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ast
>>> source = """
... with (
...     nullcontext() if bool() else nullcontext()
... ):
...     pass
... """
>>> ast.parse(source, feature_version=(3, 8))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/alexw/.pyenv/versions/3.10.6/lib/python3.10/ast.py", line 50, in parse
    return compile(source, filename, mode, flags,
  File "<unknown>", line 5
    pass
        ^
SyntaxError: Parenthesized context managers are only supported in Python 3.9 and greater

Cc. @hauntsaninja / @pablogsal

CPython versions tested on:

3.8, 3.9, 3.10, 3.11, 3.12

Operating systems tested on:

macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.11only security fixes3.12only security fixes3.13bugs and security fixesstdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions