Skip to content

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

Closed

Description

@tom-pytel

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

Activity

  1. tomasr8 commented on Feb 3, 2025

    @tomasr8
    Member

    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

  2. added
    stdlibStandard Library Python modules in the Lib/ directory
    and removed
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    on Feb 3, 2025
  3. tom-pytel commented on Feb 3, 2025

    @tom-pytel
    ContributorAuthor

    Sure, will send something up later.

  4. added a commit that references this issue on Feb 3, 2025
  5. 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[/+] on Feb 3, 2025
  6. added a commit that references this issue on Mar 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

stdlibStandard Library Python modules in the Lib/ directorytopic-parsertype-bugAn unexpected behavior, bug, or error

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions