Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Improve the constructors of AST nodes #105858

Copy link
Copy link
Closed
@JelleZijlstra

Description

@JelleZijlstra
Issue body actions

Currently, the constructors for AST nodes accept arbitrary keyword arguments and don't enforce any value:

>>> node=ast.FunctionDef(what="is this")
>>> node.what
'is this'
>>> node.name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'FunctionDef' object has no attribute 'name'

Problems with the current situation:

  • To make a correct AST node, you have to pass every attribute, including ones that could sensibly default to an empty list
  • You cannot rely on attributes like name being present
  • It's possible to create useless, broken AST nodes like the above
  • Introspection tools can't easily tell what the signature of the constructor is supposed to be
  • Adding new fields to an AST node causes various compatibility issues (PEP-695: Potentially breaking changes made to __match_args__ attributes of AST nodes #104799)

Proposed solution for 3.13:

  • Default all fields to some sensible value if they are not provided to the constructor: an empty list for list fields, and None for other fields.
  • Emit a DeprecationWarning if the constructor is passed arguments that it doesn't recognize (e.g., what above). In 3.15, this will raise an error.
  • Add a __text_signature__ to the AST classes indicating the expected signature.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.