[C++-sig] Multiple python interpreter contexts

Stefan Seefeld seefeld at sympatico.ca
Tue Feb 22 22:09:43 CET 2005


Clay Culver wrote:
> I'm trying to make two separate contexts for my embedded python 
> application.  That is, if I set some the X variable in one, it does not 
> set X in the other.  I tried to do this by copying the dictionary like 
> this:
> 
>    object mainModule(handle<>(borrowed(PyImport_AddModule("__main__"))));
>       dict pyNamespace = dict(mainModule.attr("__dict__"));
>    dict pyNamespace2 = dict(pyNamespace);

It turns out that this does a shallow copy, i.e. pyNamespace2.ptr() == pyNamespace.ptr(),
and thus modifications to one are immediately visible in the other.

I'm a bit puzzled by this, too, as comments in dict.hpp indicate:

       // dict() -> new empty dictionary.
       // dict(mapping) -> new dictionary initialized from a mapping object's
       //     (key, value) pairs.
       // dict(seq) -> new dictionary initialized as if via:

As there is no mention of the copy constructor I would assume the one that
applies is 'dict(mapping)', but it doesn't appear to. David ?

In python, you have to explicitely ask for a deep copy by calling the 'copy' method.
That should work from within C++, too, i.e.

dict pyNamespace2 = pyNamespace.copy()

HTH,
		Stefan



More information about the Cplusplus-sig mailing list