Another form of dynamic import

Marco Nawijn nawijn at
Wed Mar 25 15:23:40 CET 2009


In short I would like to know if somebody knows if it is possible to
re-execute a statement that raised an exception? I will explain the
reason by providing a small introduction on why this might be nice in
my case
and some example code.

I am using the python bindings to a *very* large C++ library. About
5000 classes divided over approx. 450 different
packages are exposed through the Python interface. To reduce the
number of import statements that need to be inserted and to limit the
number of wildcard imports it would be very helpful if class names
could be automatically imported from the proper module. There is no
problem in finding out the proper module given a (valid) class name.

As an example, look at the following statement

>> aPoint = gp_Pnt(1.0, 0.0, 0.0)     # Oops, this will raise a NameError, since
                                                      # gp_Pnt class
is unknown

NameError: name 'gp_Pnt' is not defined

As indicated, this will raise a NameError exception. What I would like
to do is something like the following (pseudo-code):

    aPoint = gp_Pnt(1.0, 0.0, 0.0)    [1]

except NameError, e:

     name = e.args[0].split[1]

     if isValid(name):
===> Can I go back to statement [1] from this point?
         raise e

There is no problem in catching the exception, finding out which name
is unknown to python and check if this is a valid name for my library.
My question is, is there any possibility of going back to the
statement that raised the error, re-execute the statement and

Thanks for any thoughts and suggestions.


More information about the Python-list mailing list