Python:使用compile/eval时出现分段错误

Python:使用compile/eval时出现分段错误,python,compilation,segmentation-fault,cpython,pypy,Python,Compilation,Segmentation Fault,Cpython,Pypy,代码: 导入ast globalsDict={} fAst=ast.FunctionDef( name=“foo”, args=ast.arguments(args=[]、vararg=None、kwarg=None、defaults=[]), body=[],decorator\u list=[]) exprAst=ast.Interactive(body=[fAst]) 修复缺少的位置(扩展) compiled=compile(exprAst,“,”单个“) eval(已编译、globals

代码:

导入ast
globalsDict={}
fAst=ast.FunctionDef(
name=“foo”,
args=ast.arguments(args=[]、vararg=None、kwarg=None、defaults=[]),
body=[],decorator\u list=[])
exprAst=ast.Interactive(body=[fAst])
修复缺少的位置(扩展)
compiled=compile(exprAst,“,”单个“)
eval(已编译、globalsDict、globalsDict)
打印globalsDict[“foo”]
对于CPython和PyPy,我遇到了一个分割错误。为什么?



我想您的函数定义不能有空的主体。我通过添加no op语句作为函数体来测试您的代码:

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"]
分段故障消失;输出为:

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

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

如果定义空函数而没有将
pass
放在函数体的开头,Python会给您一个语法错误,不是吗?确实会。这是因为目前AST没有经过验证,CPython中有一个开放的票证,当您试图编译AST时,可以向AST添加一个验证器,以避免类似的问题。 <function foo at 0x022DB3F0>