Why doesn’t exec work in a function with a subfunction?

Correct. You can’t use exec in a function that has a subfunction, unless you specify a context. From the docs:

If exec is used in a function and the
function contains a nested block with
free variables, the compiler will
raise a SyntaxError unless the exec
explicitly specifies the local
namespace for the exec. (In other
words, “exec obj” would be illegal,
but “exec obj in ns” would be legal.)

There is good reason for this which I would probably understand if it wasn’t Sunday night.
Now, next question: Why are you using exec? It’s very rarely needed. You say you have a good reason. I’m feeling sceptical about that. 😉 If you have a good reason I’ll tell you the workaround. 😛

Oh well, here it is anyway:

def test2():
    """Test with a subfunction."""
    exec 'print "hi from test2"' in globals(), locals()
    def subfunction():
        return True

Leave a Comment