[C++-sig] Inconsistency with Boost.Python code

Robert rcdailey at gmail.com
Thu Oct 9 19:47:50 CEST 2008

Stefan Seefeld wrote:
> Hi Robert,
> I believe the reason for this behavior is that an implicit cast from 
> object to dict and list will cause a copy, so you don't actually insert 
> the path into the original (global) path object, but a local copy, which 
> obviously isn't seen by the rest of the application.
> Robert wrote:
>> Hi,
>> Suppose the following C++ Boost.Python code below. Note that I am 
>> embedding the python interpreter to execute python scripts from C++:
>>     using namespace boost::python;
>>     object imported( import( "sys" ) );
>>     dict sysdict( imported.attr( "__dict__" ) );
> The call to 'attr()' returns an object, and you assign it to a dict. 
> This causes a copy. Try this instead:
> object dict_object = imported.attr("__dict__");
> dict sysdict = extract<dict>(dict_object);
>>     list syspath( sysdict["path"] );
> And likewise here:
> object list_object = sysdict["path"];
> list syspath = extract<list>(list_object);
>>     syspath.append( "C:\testing" );
> However, as you have discovered, there are ways to fold these lines to 
> make it more compact. I only spelled the individual steps out to 
> illustrate what's going on underneath.
> HTH,
>       Stefan

Thanks for your response.

Will this code below work?

	boost::python::dict GetNamespace( char const* mod )
		using namespace boost::python;
		dict moduleNamespace( extract<dict>( import( mod ).attr( "__dict__" ) ) );
		return moduleNamespace;

My main concern is the returned value of "import()" going out of scope 
and being destroyed since there are no outstanding references to it, 
causing the dict object returned to reference an invalid object. Would 
this be a possibility?

After running the code above I find that it does not work, and I get the 
following output from python:

TypeError: No to_python (by-value) converter found for C++ type: struct 
boost::python::extract<class boost::python::dict>

Not sure what this means! Thanks again for all the help!

More information about the Cplusplus-sig mailing list