I'm working on an IDE for a program I'm building, and just found out I need to use ast.

I can't seem to find any decent examples to get me started on google...
can someone help me out. :)

thanks

First thing to do is to print the structure to see what it contains. I found a pretty printer here

#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

__doc__ = '''
'''
import ast
from astpp import dump

source = """
def foo(n):
    p = 1
    while n > 0:
        p *= n
        n -= 1
    return p
"""

if __name__ == '__main__':
    result = ast.parse(source)
    print(dump(result))

""" -> my output    
Module(body=[
    FunctionDef(name='foo', args=arguments(args=[
        Name(id='n', ctx=Param()),
      ], vararg=None, kwarg=None, defaults=[]), body=[
        Assign(targets=[
            Name(id='p', ctx=Store()),
          ], value=Num(n=1)),
        While(test=Compare(left=Name(id='n', ctx=Load()), ops=[
            Gt(),
          ], comparators=[
            Num(n=0),
          ]), body=[
            AugAssign(target=Name(id='p', ctx=Store()), op=Mult(), value=Name(id='n', ctx=Load())),
            AugAssign(target=Name(id='n', ctx=Store()), op=Sub(), value=Num(n=1)),
          ], orelse=[]),
        Return(value=Name(id='p', ctx=Load())),
      ], decorator_list=[]),
  ])
"""

Next step: learn how to extract and use data from this
structure.

Unfortunately, I dont think there is a pymotw about ast :(

erg, my termage is escaping me >.<
pymotw??

but yea... best I got was the example on this page

[n.targets[0].id for n in ast.walk(ast.parse("x = struct()"))
    if isinstance(n, ast.Assign)
        and isinstance(n.value, ast.Call)
        and n.value.func.id == 'struct']

I'm intending to replace my current crappy tokenize method I developed back here

it works, but not as well as I need it to...

for right now, I'm going through some extremely complex lookback methods (such as writing my own parser) just to get the names of the things I need... >_<

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.