6

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?


1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Python gives you a syntax error if you define an empty function without putting pass in the body of the function to begin with, does it not?
It does. It won't segfault though.
This is because currently ASTs aren't validated, there's an open ticket in CPython to add a validator to ASTs when you try to compile them to avoid issues like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.