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

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()


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=[]))])