Python - ast - How to find first function
python, python-2.7
Solution
Use `ast.parse`, not `compiler.parse`:
>>> import ast
>>>
>>> code = """
... def func1():
... return 1
...
... def func2():
... return 2
... """
>>>
>>> tree = ast.parse(code)
>>> [x.name for x in ast.walk(tree) if isinstance(x, ast.FunctionDef)]
['func1', 'func2']
Problem
I'm trying to find the first function in arbitrary Python code. What's the best way to do this? Here's what I've tried so 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 an error I 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 for name, field in iter_fields(node): File "/usr/lib64/python2.7/ast.py", line 168, in iter_fields for field in node._fields: AttributeError: Module instance has no attribute '_fields' ```