Skip to content

Commit 27fc3b6

Browse files
authored
bpo-38870: Expose a function to unparse an ast object in the ast module (GH-17302)
Add ast.unparse() as a function in the ast module that can be used to unparse an ast.AST object and produce a string with code that would produce an equivalent ast.AST object when parsed.
1 parent 6bf644e commit 27fc3b6

File tree

6 files changed

+772
-751
lines changed

6 files changed

+772
-751
lines changed

Doc/library/ast.rst

+13
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,19 @@ and classes for traversing abstract syntax trees:
161161
Added ``type_comments``, ``mode='func_type'`` and ``feature_version``.
162162

163163

164+
.. function:: unparse(ast_obj)
165+
166+
Unparse an :class:`ast.AST` object and generate a string with code
167+
that would produce an equivalent :class:`ast.AST` object if parsed
168+
back with :func:`ast.parse`.
169+
170+
.. warning::
171+
The produced code string will not necesarily be equal to the original
172+
code that generated the :class:`ast.AST` object.
173+
174+
.. versionadded:: 3.9
175+
176+
164177
.. function:: literal_eval(node_or_string)
165178

166179
Safely evaluate an expression node or a string containing a Python literal or

Doc/whatsnew/3.9.rst

+5
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,11 @@ Added the *indent* option to :func:`~ast.dump` which allows it to produce a
121121
multiline indented output.
122122
(Contributed by Serhiy Storchaka in :issue:`37995`.)
123123

124+
Added the :func:`ast.unparse` as a function in the :mod:`ast` module that can
125+
be used to unparse an :class:`ast.AST` object and produce a string with code
126+
that would produce an equivalent :class:`ast.AST` object when parsed.
127+
(Contributed by Pablo Galindo and Batuhan Taskaya in :issue:`38870`.)
128+
124129
asyncio
125130
-------
126131

0 commit comments

Comments
 (0)