Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: getting segmentation fault when using compile/eval

Code:

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"]

With both CPython and PyPy, I am getting a segmentation fault. Why?


  • CPython bug report
  • PyPy bug report
  • Abstract Syntax Trees documentation
like image 242
Albert Avatar asked Jul 21 '11 15:07

Albert


1 Answers

I guess that your function definition must not have an empty body. I tested your code by adding a no-op statement as the function body:

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

And the segmentation fault is gone; output is:

<function foo at 0x022DB3F0>

If I am correct, this could be a bug in the ast module, since it should check for the empty body.

like image 154
Ferdinand Beyer Avatar answered Sep 27 '22 22:09

Ferdinand Beyer