Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - ast - How to find first function

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'
like image 899
Greg Avatar asked Sep 12 '25 16:09

Greg


1 Answers

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']
like image 168
falsetru Avatar answered Sep 14 '25 06:09

falsetru