How to eval a file
Alex Martelli
aleax at aleax.it
Sun Feb 23 05:20:54 EST 2003
Björn Lindberg wrote:
...
> I see now. BTW, isn't it a bit strange that the eval syntax is
> eval(<expr>), whereas exec is written without parantheses, exec
> "<statement>"?
No, because eval is a function while exec is a statement.
All functions are always called with parentheses.
Statements never _demand_ parentheses EXCEPT the 'def' statement
(which parallels function-call in this way) -- and 'class' if
it involves bases classes.
> Ah, I see now. I thought that by just doing "execfile(filename)", the
> variables would automagically appear in the local namespace. The
They do, and that is exactly why you should not use it that way:
you completely lose control of what's defined in your local namespace
after that. It makes errors likely and debugging far too hard.
> You are right. I was trying to take advantage of the fact that I am
> using a very high level language. But still, there are fewer security
> implications and more error checking by parsing it manually. I think I
> will use the execfile() solution for now, and when it gets closer to
> being finished, I will write a proper parser instead.
This is a reasonable compromise. But make sure you use execfile
WITH an explicit namespace anyway -- even just to debug &c -- you'll
be glad you did.
Alex
More information about the Python-list
mailing list