Exec Statement Question
Carsten Haese
carsten.haese at gmail.com
Mon Nov 30 11:25:29 EST 2009
Victor Subervi wrote:
> Taking out the parenthesis did it! Thanks. Now, you state this is an
> option of last resort. Although this does indeed achieve my desired aim,
> here is a complete example of what I am trying to achieve. The following
> is from 'createTables2.py':
>
> for table in tables:
> try:
> exec 'from options import %s' % table
> except:
> pass
> try:
> exec '%s()' % table
> except:
> pass
Here's a rough sketch of rewriting that snippet in a way that uses
attribute lookup instead of dynamic code execution:
#---------------------------------------#
import options
for table in tables:
tablefunc = getattr(options, table)
tablefunc()
#---------------------------------------#
The main ideas behind this approach are:
1) Rather than importing the functions from the options module piecemeal
into the local namespace, I just import the entire options module as its
own separate namespace.
2) I use getattr on that separate namespace to look up the desired
function object from the options module. I assign the local name
<<tablefunc>> to the resulting function object.
3) I call that function using the local name <<tablefunc>>.
HTH,
--
Carsten Haese
http://informixdb.sourceforge.net
More information about the Python-list
mailing list