[C++-sig] Re: Injecting python code to a class

Raoul Gough RaoulGough at yahoo.co.uk
Mon Mar 29 00:36:47 CEST 2004


"Ralf W. Grosse-Kunstleve" <rwgk at yahoo.com> writes:

> Hi from Cambridge, UK :)

Well, hi from South-East London!

>
> This might not be what you are after, but anyway:
>
> I inject methods from Python all the time using a
> "boost.python.injector" similar to the one mentioned in the
> Boost.Python tutorial. For example:
>
> http://cvs.sourceforge.net/viewcvs.py/cctbx/scitbx/scitbx/math/gaussian.py?rev=1.7&view=auto
>
> The injector is defined here:
>
> http://cvs.sourceforge.net/viewcvs.py/cctbx/boost_adaptbx/boost/python.py?rev=1.1&view=auto
>
> All my extension module imports go through a Python layer to work
> around exception handling problems with certain versions of gcc, and
> because I add all kinds of stuff from Python anyway. Therefore the
> injector doesn't add any extra complications. If you don't want the
> Python layer I'd write the extra functions in C++ using the
> boost::python::object facilities. Just loop over your array in C++
> and append str(element) to a boost::python::list.

Yes, doing it with a loop in C++ is certainly an option, but I was
hoping to avoid this becuase of the simplicity of the Python
solution. The C++ code would have to rely heavily on Python facilities
like list and str, as you suggest, since client code might have
provided Python __str__ or __repr__ methods for the container
elements.

I had a quick look at the injector code you mentioned, but that seems
to rely on Python code as well. Not that that's a bad thing, but I'm
looking for a solution to embed within the C++ extension module code,
which was my original problem - how to insert some Python code as a
method from within the C++ code.

> BTW: I believe an array __repr__ that spits out the entire array is
> a very bad idea. If the user bothers to make a C++ array instead of
> simply using a Python list the C++ array is probably big, and the
> __repr__ output will be a nuisance because of its size. Seeing the
> default __repr__ output is more helpful. If the user really wants
> the content, print list(array_instance) will do the trick.  If the
> wrapped arrays are small it is IMO much more efficient (compile-time
> and object code size) to use the "tuple_mappings". See FAQ, mention
> of scitbx in connection with array wrappers.

Well, I guess it's debatable whether the C++ containers should provide
__str__ and __repr__, but I was thinking along the lines of providing
a near-complete emulation of Python sequences, and "least surprise" on
the Python side.

-- 
Raoul Gough.
export LESS='-X'





More information about the Cplusplus-sig mailing list