IndentationError during `ast.parse` and `ast.walk` of a function which is a method inside class

IndentationError during `ast.parse` and `ast.walk` of a function which is a method inside class

我想我知道 IndentationError 的常见原因,例如 IndentationError: unindent does not match any outer indentation level 中所述。这不适用于此处。

此外,我知道 textwrap.dedent 但我觉得这不是正确的方法?


如果我有一个 "regular" 函数,我可以这样 ast.parseast.walk

import ast
import inspect

def a():
    pass

code = inspect.getsource(a)
nodes = ast.walk(ast.parse(code))
for node in nodes:
    ...

但是,如果函数是class中的一个方法,比如:

class B:
    def c(self):
        pass

code = inspect.getsource(B.c)
nodes = ast.walk(ast.parse(code))

我得到:

IndentationError: unexpected indent

我想这是有道理的,因为 B.c 缩进一级。那么我如何 ast.parseast.walk 在这里呢?

这是因为您抓住了方法,而不是尝试在不撤消缩进的情况下执行它。 您的 class 是:

class B:
    def c(self):
        pass

code = inspect.getsource(B.c)
nodes = ast.walk(ast.parse(code))

如果你打印 code 你会看到:

    def c(self):
        pass

注意:以上代码有一处缩进。你需要un-indent它:

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))