开发者

Given an AST, is there a working library for getting the source?

Is there a way to convert a given Python abstract syntax tree (AST) to a source code?

Here is a good example of how to use Python's ast module, specif开发者_C百科ically a NodeTransformer. I was looking for a way to convert the resulting AST back to source, so the changes can be inspected visually.


The Python source tree contains an implementation of this: unparse.py in the Demo/parser directory

Editor's note: With the introduction of ast.unparse() in Python 3.9, unparse.py has been removed, so the above link has been updated to point to 3.8.


A nice third-party library I found: astunparse which is based on the unparse.py suggested by Ned in his answer. Example:

import ast
import astunparse

code = '''
class C:
    def f(self, arg):
        return f'{arg}'

print(C().f("foo" + 'bar'))
'''

print(astunparse.unparse(ast.parse(code)))

running which yields

class C():

    def f(self, arg):
        return f'{arg}'
print(C().f(('foo' + 'bar')))

Another neat function is astunparse.dump which pretty-prints the code object:

astunparse.dump(ast.parse(code))

Output:

Module(body=[
  ClassDef(
    name='C',
    bases=[],
    keywords=[],
    body=[FunctionDef(
      name='f',
      args=arguments(
        args=[
          arg(
            arg='self',
            annotation=None),
          arg(
            arg='arg',
            annotation=None)],
        vararg=None,
        kwonlyargs=[],
        kw_defaults=[],
        kwarg=None,
        defaults=[]),
      body=[Return(value=JoinedStr(values=[FormattedValue(
        value=Name(
          id='arg',
          ctx=Load()),
        conversion=-1,
        format_spec=None)]))],
      decorator_list=[],
      returns=None)],
    decorator_list=[]),
  Expr(value=Call(
    func=Name(
      id='print',
      ctx=Load()),
    args=[Call(
      func=Attribute(
        value=Call(
          func=Name(
            id='C',
            ctx=Load()),
          args=[],
          keywords=[]),
        attr='f',
        ctx=Load()),
      args=[BinOp(
        left=Str(s='foo'),
        op=Add(),
        right=Str(s='bar'))],
      keywords=[])],
    keywords=[]))])


As of Python 3.9, the ast module provides an unparse function for this:

Unparse an ast.AST object and generate a string with code that would produce an equivalent ast.AST object if parsed back with ast.parse()


Have a look at http://pypi.python.org/pypi/sourcecodegen/0.6.14

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜