Embedding: how to extend a C++ instance by Python methods

Alex Martelli aleax at aleax.it
Mon Jul 8 17:50:06 EDT 2002


Renzo Tomaselli wrote:
        ...
> A key point is that I want users to be able defining just method
> bodies, not to play around with entire modules. For this reason I
> would like to implement the housekeeping details in C++ as much as
> possible.

This second sentence does not follow from the first.  You can
perfectly well implement all housekeeping details in Python (and
make your life substantially simpler thereby) without burdening
your users with having to do anything more than "adding method
bodies".

> What I miss here is about creating callable objects from these stored
> declarations, so that they can be added to instances and invoked on
> the fly.

Executing (in a specific 'local' dictionary, and possibly after prepending 
'def ' or whatever you don't want the users to have to type) the 
declarations will give you the function objects.  Adding them to
instances (rather than types or classes) is one possibility, which will 
work to some extent, but not without problems -- you'd need to
set up a closure and play some dirty tricks to get the 'self' passed
in.  Simplest is always to add to a class -- as long of course as the
later invocation is also done from Python -- possibly an otherwise
empty subclass built on the fly just for the purpose, if need be.


Alex





More information about the Python-list mailing list