[C++-sig] importing C++ module fails, but module is still in sys.modules

Roman Yakovenko roman.yakovenko at gmail.com
Sun Jul 13 09:59:10 CEST 2008


On Fri, Jul 11, 2008 at 9:19 PM, Moe Goldberg <goldberg at coredp.com> wrote:
> I'm not sure if this is just a quirk in python, of if I am doing something
> wrong.
> If a C++ extension module throws an exception while it's initializing, the
> module is still stored in sys.modules (as opposed to a python module, which
> is not stored in sys.modules if it errors while being imported).
>
> For example:
>
> pymodule.py:
> raise RuntimeError("This python module fails.")
>
> cppmodule.cpp:
> #include <boost/python.hpp>
> #include <stdexcept>
> BOOST_PYTHON_MODULE(cppmodule)
> {
>   throw std::runtime_error("This C++ module fails.");
> }
>
>>>> import pymodule
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>  File "pymodule.py", line 2, in ?
>   raise RuntimeError("This python module fails.")
> RuntimeError: This python module fails.
>
>>>> import cppmodule
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
> RuntimeError: This C++ module fails.
>
>>>> include sys
>>>> 'pymodule' in sys.modules
> False
>>>> 'cppmodule' in sys.modules
> True
>
> Is there a sane way to prevent pymodule from being added to sys.modules if
> importing it fails?

It has nothing to do with boost.python. Same thing will happen with
pure Python module too.

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list