[C++-sig] Derivation from Python str

Willi Karel wk at ipf.tuwien.ac.at
Wed Sep 29 17:02:57 CEST 2010


I'd like to derive from either Python's built-in 'str' or
boost::python::str, resulting in a class that provides additional
methods / member functions / attributes. The definitions of these
additional methods are implemented in C++. Is there any way to achieve
that? Please note that implicit conversions don't serve this goal, as
methods of 'str' should be part of the derived classes set of attributes
- e.g. the following Python code should be ok ('Derived' being the class
derived from Python's 'str'):

>>> Derived d
>>> d.startswith('prefix')

I see that Python's 'str' is immutable, which is acceptable for my purpose.

What I tried:

Including e.g. boost::python::str in the list of base classes yields a
run-time error in python:
boost::python::class_<Derived, boost::python::bases< boost::python::str
> >("Derived")
.def("foo",&Derived::foo)
;

Including std::string (which is built-in-converted to Python's 'str') in
the list of base classes yields a run-time assertion complaining about
the base class not having been wrapped. What I'd like to achieve anyway,
is derivation from Python's 'str', not std::string.

Thanks for any help!
Cheers, Willi.


More information about the Cplusplus-sig mailing list