[Tutor] eval and exec
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Sat Dec 4 23:51:50 CET 2004
Bill Campbell wrote:
> On Sat, Dec 04, 2004, Alan Gauld wrote:
>
>>>I'm having trouble understanding the difference between eval and
>>
>>exec.
>>
>>eval evaluates an *expression* - that is something that returns a
>>value.
>>
>
> ...
>
>>Both are extremely dangerous functions from a security
>>and maintenance/reliability pouint of view and should be
>>used very rarely.
>
>
> True enough, but useful upon occassion. In particular I've had a
> question on the back burner for a while. Suppose I have a
> dictionary of database instances, dbtables, keyed on table name,
> and I want a general way of creating variables with the name of
> the table so I'm not accessing the dictionary. Would something
> like this work:
>
> # dbtables is already built
> for table in dbtables.keys():
> exec("%s = dbtables['%s']" % (table, table))
>
Yes it works, since it sticks that binding in the module namespace. But
the question is, why would you want to do that? You already have the
names in the dictionary... and to round off the irony, namespaces in
Python are implemented as dictionaries! Is there a compelling reason why
you need this?
As has been already said, the thumbrule is that exec and it's brother
eval are to be used in only a very few specialized situations. For
example, giving the oportunity to the user of an application to interact
directly with it via Python code. For the majority of the situations
there is always a better (and faster and...) solution.
With my best regards,
G. Rodrigues
More information about the Tutor
mailing list