Skip to content

Improve repr() of AST nodes #116022

@JelleZijlstra

Description

@JelleZijlstra

Feature or enhancement

Proposal:

I often use ast.parse in the terminal to explore what the AST looks like:

>>> ast.parse("x = 3")
<ast.Module object at 0x105450b50>

But I have to remember to use ast.dump() to get useful output:

>>> ast.dump(ast.parse("x = 3"))
"Module(body=[Assign(targets=[Name(id='x', ctx=Store())], value=Constant(value=3))], type_ignores=[])"

It would be nice if the default repr() of AST nodes was more like the output of ast.dump(), so it's easier to see at a glance how it works.

One concern would be around the size of the output:

>>> from pathlib import Path
>>> import typing
>>> typing_py = Path(typing.__file__).read_text()
>>> len(ast.dump(ast.parse(typing_py)))
304244

As a middle ground, we could limit the depth of the AST provided in the repr(), e.g. to 2 levels, and also the number of list elements provided.

The repr() of a module's AST might then look something like:

Module(body=[Expr(value=Constant(...)), ..., Assign(targets=[Name(...)], value=Constant(...))], type_ignores=[])

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtopic-parsertype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy