[C++-sig] wrapping operator=

William Ladwig wladwig at wdtinc.com
Mon May 25 18:54:53 CEST 2009

Generally how that situation is handled on the Python side is to use the container emulation API, so that assigning all values would look like this to a user of your class:

data[:] = 42.

To do this, you just need to write a small c++ wrapper to expose the __setitem__(self, key, value) function, which accepts (or extracts) a slice object for the key and then calls your class operator= function.  Or, you could just stick with the assign function that you created, which may be better if your class isn't supposed to look like a container.  This may actually be less error prone.

Here is the Python container emulation documentation:


Other people may have better suggestions.  


From: cplusplus-sig-bounces+wladwig=wdtinc.com at python.org [cplusplus-sig-bounces+wladwig=wdtinc.com at python.org] On Behalf Of Hans Roessler [hansroessler at yahoo.de]
Sent: Monday, May 25, 2009 9:08 AM
To: cplusplus-sig at python.org
Subject: [C++-sig] wrapping operator=

I want to wrap with boost.python a C++ class "DataCube" which has overloaded the operator=.

The  constructor DataCube::DataCube(double x) allocates huge amounts of memory and fills it with x's.
The  DataCube::operator=(double x) just overwrites the already allocated memory with x's.

Now in C++ these commands first allocate memory, which is filled with 0.'s, and then overwrite the memory with 42.'s:
>DataCube data(0.)

In Python these commands first build the DataCube as desired, but then set data=42. (now data is a float), where the reference to the DataCube is lost:

I have circumvented this by replacing the second line with
> data.assign(42.)
with a function assign which is defined appropriately, but I would prefer to use the same assignment as in C++.

Finally the question:
Can I define the DataCube class in Python, so that the data variable above will behave as in C++, when I write "data=42." ?
In other words, is there any possibility in Python that "x=y" does NOT make x a reference to y?

Thank you

Cplusplus-sig mailing list
Cplusplus-sig at python.org

More information about the Cplusplus-sig mailing list