Closed
Description
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
Labels
Python modules in the Lib dirPython modules in the Lib dirA feature request or enhancementA feature request or enhancement