Skip to content

ast.parse(..., mode='single') parses of multiple statements which are then not unparsed #129598

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tom-pytel opened this issue Feb 2, 2025 · 2 comments
Assignees
Labels
stdlib Python modules in the Lib dir topic-parser type-bug An unexpected behavior, bug, or error

Comments

@tom-pytel
Copy link
Contributor

tom-pytel commented Feb 2, 2025

Bug report

Bug description:

$ ./python
Python 3.14.0a4+ (heads/test:d906bde250, Feb  2 2025, 11:08:38) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ast
>>> a = ast.parse('i = 1; j = 2', mode='single')
>>> print(ast.dump(a, indent=2))
Interactive(
  body=[
    Assign(
      targets=[
        Name(id='i', ctx=Store())],
      value=Constant(value=1)),
    Assign(
      targets=[
        Name(id='j', ctx=Store())],
      value=Constant(value=2))])
>>> ast.unparse(a)
'j = 2'

My guess the ast.parse() should probably error?

CPython versions tested on:

3.14, 3.12, 3.13, 3.11, 3.10

Operating systems tested on:

Linux

Linked PRs

@tom-pytel tom-pytel added the type-bug An unexpected behavior, bug, or error label Feb 2, 2025
@picnixz picnixz added the interpreter-core (Objects, Python, Grammar, and Parser dirs) label Feb 2, 2025
@tomasr8
Copy link
Member

tomasr8 commented Feb 3, 2025

mode='single' is for Interactive input which always returns ast.Interactive. i = 1; j = 2 is a valid interactive_input.

It looks like we are missing a specialized visit_Interactive in the _Unparser visitor:

cpython/Lib/ast.py

Lines 666 to 669 in 808071b

class _Unparser(NodeVisitor):
"""Methods in this class recursively traverse an AST and
output source code for the abstract syntax; original formatting
is disregarded."""

Would you like to fix this? Otherwise I can send a fix later

@picnixz picnixz added stdlib Python modules in the Lib dir and removed interpreter-core (Objects, Python, Grammar, and Parser dirs) labels Feb 3, 2025
@tom-pytel
Copy link
Contributor Author

Sure, will send something up later.

tom-pytel added a commit to tom-pytel/cpython that referenced this issue Feb 3, 2025
@brettcannon brettcannon changed the title ast.parse(..., mode='single') parses of multiple statements which are then not unparsed ast.parse(..., mode='single') parses of multiple statements which are then not unparsed Feb 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stdlib Python modules in the Lib dir topic-parser type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

4 participants