[Tutor] eval and exec

Bill Campbell bill at celestial.net
Sun Dec 5 02:20:25 CET 2004


On Sat, Dec 04, 2004, Gonçalo Rodrigues wrote:
>Bill Campbell wrote:
...
>>>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?

Primarily because it's easier to type, thus less prone to errors.  A
secondary reason is that I'm in the process of converting an accounting
application, written in C, to use a python front end, and the source code
requires less modification doing it this way.

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

``Most people, sometime in their lives, stumble across truth. Most jump
up, brush themselves off, and hurry on about their business as if
nothing had happened.'' - Sir Winston Churchill


More information about the Tutor mailing list