Can Python do this?
Gerhard Häring
gerhard at bigfoot.de
Tue Mar 5 09:54:34 EST 2002
Giorgi Lekishvili wrote:
> Gerhard Häring wrote:
>>Le 04/03/02 à 12:51, Robert Oschler écrivit:
>>> [calling a function by name]
>>This can easily be done with the built-ins eval and exec. But in 99 % of
>>all cases, it's a really bad idea to use them. Perhaps you can tell us
>>what you're trying to accomplish anyway? There's usually a better way
>>than (ab)using eval/exec > Hi!
>
> Can you tell me little bit more why is this a bad idea to use exec/eval?
Because they're
- unnecessary
- ugly
- unsafe
The defaults of exec and eval use the locals() and globals() of the
environment they're executed in. This can lead to problems that are
quite difficult to debug. So, if use them at all, most probably better
give them arguments for the local and global dictionary, too.
The reason I don't like them is that they're can almost always be
replaced by an indrection, like a dictionary that maps to functions.
Using eval/exec may be a quick hack for not having to think of a real
algorithm, but IMHO you're only getting ugly and difficult-to-understand
code. Btw. I used to think I need exec to import modules dynamically,
but for this special case, there's an __import__ builtin that does just
this.
Also it's a big no-no to run any code that you can't absolutely trust in
exec/eval. If one really need to do this (again: I'd say chances are 99
% that you don't ;-), one better takes a look at the bastion module before.
> Where can I find more information?
I think you can fnid better explanations on http://groups.google.com/
I've seen this discussed here more than once.
Here's a post from Alex Martelli, for example:
http://groups.google.com/groups?as_umsgid=9hlhkl02cu9%40enews1.newsguy.com&hl=en
In the end, I'm thinking of eval/exec as a last resort, if all
OOP/structural programming ways to solve a problem would be too much a
PITA. Think of it like gotos and casts to void* in C, too much of it and
you have an ugly unmaintainable mess.
ciao,
Gerhard
More information about the Python-list
mailing list