[Tutor] eval and exec
alan.gauld at freenet.co.uk
Sun Dec 5 09:56:51 CET 2004
> 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))
It will create a lot of variables named after your tables.
The problem with this approach is how will the code that comes
after this dynamic naming know about those names which don't
exist when you wrote it?
You can only access variables that you know exist, but if
you know they will exist you don't need to do the dynamic
So this approach is only useful where you know a lot of
names in advance but don't want to go to the hassle of
explicitly initialising them all before using them. The cost
of this small time saving is the use of a potentially
dangerous exec call.
This kind of dynamic naming scheme is only really useful
in some kind of interactive session, when you run a program
thats written in advance it is much better to put dynamically
created objects into a collection IMHO.
More information about the Tutor