Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
I think I'm aware of the usual causes for
IndentationError
like described in
IndentationError: unindent does not match any outer indentation level
for example. This doesn't apply here.
Also, I know about
textwrap.dedent
but it doesn't feel like it's the right approach here?
If I have a "regular" function, I can do
ast.parse
and
ast.walk
like this:
import ast
import inspect
def a():
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):
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?
–
–
–
Its because you grabbed the method than tried walking it without undoing the indents.
Your class is:
class B:
def c(self):
code = inspect.getsource(B.c)
nodes = ast.walk(ast.parse(code))
If you print code
you see:
def c(self):
Note: The above code has one indent. You need to un-indent it:
import inspect
import ast
import textwrap
class B:
def c(self):
code = textwrap.dedent(inspect.getsource(B.c))
nodes = ast.walk(ast.parse(code))
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.