Search code examples
pythonstringpretty-print

printing a string with function calls


I have a ast.dump like so:

"Module(body=[Assign(targets=[Name(id='i', ctx=Store())], value=Num(n=0)), While(test=Compare(left=Name(id='i', ctx=Load()), ops=[Lt()], comparators=[Num(n=10)]), body=[Print(dest=None, values=[Name(id='i', ctx=Load())], nl=True), AugAssign(target=Name(id='i', ctx=Store()), op=Add(), value=Num(n=1))], orelse=[]), For(target=Name(id='x', ctx=Store()), iter=Call(func=Name(id='range', ctx=Load()), args=[Num(n=10)], keywords=[], starargs=None, kwargs=None), body=[Print(dest=None, values=[Name(id='x', ctx=Load())], nl=True)], orelse=[])])"

How do I (pretty) print it in a more readable form like the one below??

Module(
       body=[Assign(targets=[Name(id='i',
                                  ctx=Store())],
                    value=Num(n=0)),
             While(test=Compare(left=Name(id='i',
                                          ctx=Load()),
                                ops=[Lt()],
                   comparators=[Num(n=10)]),
                   body=[Print(dest=None,
                               values=[Name(id='i',
                                            ctx=Load())],
                               nl=True),
                         AugAssign(target=Name(id='i',
                                               ctx=Store()),
                                   op=Add(), 
                                   value=Num(n=1))], 
                         orelse=[]),
             For(target=Name(id='x', 
                             ctx=Store()),
                 iter=Call(func=Name(id='range',
                                     ctx=Load()), 
                           args=[Num(n=10)],
                           keywords=[], 
                           starargs=None,
                           kwargs=None),
                 body=[Print(dest=None, 
                             values=[Name(id='x',
                                          ctx=Load())], 
                             nl=True)],
                 orelse=[])])

Incase you are wondering what code generated this:

text = '''
i = 0

while i < 10:
   print i
   i += 1
for x in range(10):
   print x
'''
ast.dump(ast.parse(text))

Solution

  • It's already done, for example by this function or astpp module.

    The latter one from this code:

    import ast
    import astpp
    
    tree = ast.parse(
    """
    print "Hello World!"
    s = "I'm a string!"
    print s
    """)
    print astpp.dump(tree)
    

    should produce this output:

    Module(body=[
        Print(dest=None, values=[
            Str(s='Hello World!'),
          ], nl=True),
        Assign(targets=[
            Name(id='s', ctx=Store()),
          ], value=Str(s="I'm a string!")),
        Print(dest=None, values=[
            Name(id='s', ctx=Load()),
          ], nl=True),
      ])