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
B.c
at runtime, which may be a good thing or bad thing.dedent
as it doesn't work in all cases. I've actually seen a library that used it and people who used that library ran into the edge case and reported a bug that took a while to figure out. Basically it's easy for B.c to contain some code which is less indented than thedef c
part. So if you want something that works in all cases you'll need another solution. But you'll also need to explain your use case some more as the solution will depend on that. See my comment above, for example.