Python - ast - How to find first function -


i'm trying find first function in arbitrary python code.

what's best way this?

here's i've tried far.

import ast import compiler.ast  code = """\ def func1():     return 1  def func2():     return 2  """  tree = compiler.parse(code)  print list(ast.walk(tree)) 

but i'm getting error don't understand.

traceback (most recent call last):   file "test.py", line 15, in <module>     print list(ast.walk(tree))   file "/usr/lib64/python2.7/ast.py", line 215, in walk     todo.extend(iter_child_nodes(node))   file "/usr/lib64/python2.7/ast.py", line 180, in iter_child_nodes     name, field in iter_fields(node):   file "/usr/lib64/python2.7/ast.py", line 168, in iter_fields     field in node._fields: attributeerror: module instance has no attribute '_fields' 

use ast.parse, not compiler.parse:

>>> import ast >>>  >>> code = """ ... def func1(): ...     return 1 ...  ... def func2(): ...     return 2 ... """ >>>  >>> tree = ast.parse(code) >>> [x.name x in ast.walk(tree) if isinstance(x, ast.functiondef)] ['func1', 'func2'] 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -