[C++-sig] How to define a Python metaclass with Boost.Python?
paulc.mnt at gmail.com
Wed Feb 8 15:24:13 CET 2012
> ---------- Forwarded message ----------
> From: Jim Bosch <talljimbo at gmail.com>
> To: Development of Python/C++ integration <cplusplus-sig at python.org>
> Date: Tue, 07 Feb 2012 11:14:54 -0500
> Subject: Re: [C++-sig] How to define a Python metaclass with Boost.Python?
> On 02/07/2012 01:35 AM, paulcmnt wrote:
>> The Python C API has the `PyObject *PyType_Type` object, which is
>> to `type` in the interpreter. If I want to define a metaclass in C++, how
>> can I set `type` as one of its bases in Boost.Python? Also, what other
>> things should I take into consideration when defining a Python metaclass
>> C++? It'd be ideal if there was a Boost.Python solution to this. If not, a
>> solution that uses the Python C API (or a combination of Boost and the C
>> API) is good as well. (The version I'm using is Python 3.)
> I'm afraid this isn't really supported. All Boost.Python classes have to
> use a specific Boost.Python metaclass that's defined deep in the bowels of
> some Boost.Python source file, and there's really no way to override that
> at present.
> This might be a nice feature for the future, but I haven't thought too
> deeply about how to make it work or why one would want to do it. If you
> have a specific use case for a custom metaclass, I'd love to hear what it
In my application I have a base Event class and both C++ and Python inherit
from this base and define new types of events. Clients can subscribe a
certain function to a certain type of event.
>>> events = EventDispatcher()
>>> sub = events.subscribe(KeyboardEvent, on_keyboard_event)
When an event is posted to the EventDispatcher (from either C++ or Python),
all functions that are subscribed to that event, *or to a base of that event
*, are called.
Because of how the system is supposed to work, I need a common way to
determine type and parents of an event at runtime, regardless of whether
the event class was defined in C++ or Python; I do this with a custom
The metaclass that I would like to define in C++ would add a
__cpp_event_typeinfo attribute to each event class defined in Python, which
I can then grab when I need it.
*A possible solution.* I though a good enough way of defining a metaclass
in Boost.Python would be to the equivalent of this code below. Do you think
there are any safety problem with doing something like this,
some compatibly problem that could arise with the other Boost.Python
>>> class Meta:
>>> Meta = type(Meta.__name__, (type,), dict(Meta.__dict__))
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Cplusplus-sig