6

代码:

import ast

globalsDict = {}

fAst = ast.FunctionDef(
    name="foo",
    args=ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]),
    body=[], decorator_list=[])

exprAst = ast.Interactive(body=[fAst])
ast.fix_missing_locations(exprAst)
compiled = compile(exprAst, "<foo>", "single")
eval(compiled, globalsDict, globalsDict)

print globalsDict["foo"]

使用 CPython 和 PyPy,我遇到了分段错误。为什么?


4

1 回答 1

5

我猜你的函数定义不能有一个空的主体。我通过添加一个无操作语句作为函数体来测试您的代码:

fAst = ast.FunctionDef(
    # ...
    body=[ast.Pass()],
    # ...

并且分段错误消失了;输出是:

<函数 foo 在 0x022DB3F0>

如果我是正确的,这可能是ast模块中的一个错误,因为它应该检查空体。

于 2011-07-21T15:56:34.397 回答