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

Moe Goldberg goldberg at coredp.com
Tue Jul 15 19:17:03 CEST 2008



Roman Yakovenko wrote:
> 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.
>
>   
It does not happen with a pure python module (as my example above 
indicates). Do you mean that it happens with a regular C extension 
module that doesn't use boost.python?



More information about the Cplusplus-sig mailing list