Reputation: 11282
If I have a "regular" function, I can do ast.parse
and ast.walk
like this:
import ast
import inspect
def a():
pass
code = inspect.getsource(a)
nodes = ast.walk(ast.parse(code))
for node in nodes:
...
However, if the function is a method inside a class like:
class B:
def c(self):
pass
code = inspect.getsource(B.c)
nodes = ast.walk(ast.parse(code))
I get:
IndentationError: unexpected indent
Which makes sense, I guess, since B.c
is indented by one level. So how do I ast.parse
and ast.walk
here instead?
It seems like simply calling textwrap.dedent
is not the right approach here, because it doesn't work if the code looks like this:
class B:
def c(self):
"""
foo
"""
pass
Upvotes: 2
Views: 3089
Reputation: 7897
Its because you grabbed the method than tried walking it without undoing the indents. Your class is:
class B:
def c(self):
pass
code = inspect.getsource(B.c)
nodes = ast.walk(ast.parse(code))
If you print code
you see:
def c(self):
pass
Note: The above code has one indent. You need to un-indent it:
import inspect
import ast
import textwrap
class B:
def c(self):
pass
code = textwrap.dedent(inspect.getsource(B.c))
nodes = ast.walk(ast.parse(code))
Upvotes: 11