Passing compile(...,'exec') code to 'eval'
In preparations for my coding my thesis I have been trying to figure out how a local variable could be assigned to without me explicitly knowing during compilation. Obviously 'exec' can. But I wasn't sure about 'eval'. Reading the docs, I didn't think it could since 'eval', when taking a string, only evaluates expressions. But what about code objects? The docs say, "The code object must have been compiled passing 'eval' as the kind argument". But I didn't read that when I started testing. This is when I discovered you *can* pass in something using 'compile' with the kind argument of "exec"::
x Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'x' is not defined [16425 refs] eval(compile("x = 1", "<string>", "exec")) [16426 refs] x 1
Is this a bug, or are the docs wrong? I am hoping it is the former since if it is the latter my thesis just got a big caveat pasted into it about how 'eval' can cause problems and invalidate the type inferencing in irreparable ways. -Brett
This is when I discovered you *can* pass in something using 'compile' with the kind argument of "exec"::
x Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'x' is not defined [16425 refs] eval(compile("x = 1", "<string>", "exec")) [16426 refs] x 1
Is this a bug, or are the docs wrong? I am hoping it is the former since if it is the latter my thesis just got a big caveat pasted into it about how 'eval' can cause problems and invalidate the type inferencing in irreparable ways.
You shouldn't do this, and if you do, you will pay for your sin in a special kind of hell set aside for people who take the implementation as the spec. It's hard to detect such undefined usage without making eval() (and possibly everything) slower though. --Guido van Rossum (home page: http://www.python.org/~guido/)
Hello Brett, On Wed, May 05, 2004 at 11:23:16AM -0700, Brett C. wrote:
Is this a bug, or are the docs wrong? I am hoping it is the former since if it is the latter my thesis just got a big caveat pasted into it about how 'eval' can cause problems and invalidate the type inferencing in irreparable ways.
There is another improbable way to bind variables with eval, with list comprehensions:
eval("[x for x in [3]]") [3] x 3
If the goal is not security but type inference, I guess both this and the compile() trick should be considered as outside any reasonable spec. A bientot, Armin.
participants (3)
-
Armin Rigo
-
Brett C.
-
Guido van Rossum