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

Raoul Gough RaoulGough at yahoo.co.uk
Sun Mar 28 18:52:48 CEST 2004


I'd like to add the __repr__ and __str__ methods to container classes
(in the indexing suite) and the easiest way to implement them is in
Python, e.g.

def list_repr(container):
    return repr([x for x in container])

It is possible to inject this into an existing Python class
(e.g. "container") as follows:

container.__repr__ = new.instancemethod (list_repr, None, container)

I've been trying to do something like this from C++ code, but I don't
have much experience with embedding Python code in C++, and can't see
the easy way to do it. I've tried the following:

  class_< std::vector<int> > vector_int ("vector_int");

  vector_int.def (indexing::container_suite< std::vector<int> >());

  handle<> lambda_handle
    (PyRun_String ("lambda v: repr([x for x in v])"
                   , Py_single_input, object().ptr(), object().ptr()));

  objects::add_to_namespace (vector_int, "__repr__", object(lambda_handle));

i.e. passing None for the global and local dicts to PyRun_String, but
this produces the following error during module initialization
(wrapped for legibility):

>>> from example import vector_int
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
SystemError: C:\Code\22\Objects\frameobject.c:235:
   bad argument to internal function


Is there an easy way to get at the right global and local dicts for
the PyRun_String call? I'm not sure that this would work even if I
could pass the right parameters there, so is there a better way
altogether to do this?

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





More information about the Cplusplus-sig mailing list