Subtyping a non-builtin type in C/C++

johan2sson at gmail.com johan2sson at gmail.com
Mon Aug 7 19:11:07 EDT 2006


Martin v. Löwis wrote:
> johan2sson at gmail.com schrieb:
> > I am trying to create a subclass of a python class, defined in python,
> > in C++, but I am having some problems.
>
> Is the base class a classic class or a new-style class? Depending on
> the answer, the code you should write varies significantly.
>
> To create a new type, it might be easiest to do the same as the
> interpreter. Take, for example, a look at the code that gets executed
> for new.classobj("Foo", (), {}).

I deleted my post once I realized that I had been setting tp_bases when
I should have been setting tp_base. As it turns out, that's not the end
of my problems.

I have looked in classobject.c, which I hope is the code you are
referring to, but that doesn't really solve my problem since it assumes
you have the correct base pointers and if I did I would be having a
different problem! Anyway, back to the current one:

The class I am trying to subclass is code.InteractiveConsole. With
tp_base set to the result of
PyMapping_GetItemString(PyModule_GetDict(code_module),
"InteractiveConsole"), PyType_Ready fails with an AttributeError with a
"value" of "mro" and looking at the structure in a debugger just before
the call to PyType_Ready makes me think it's corrupted somehow
(nonprintable name and clearly uninitialized fields).

I can however create an instance by calling PyObject_CallFunction on
that object. If I do, it's type (ob_type->tp_name) will be "instance".
Of course, I don't know the python type system that well, but I must
confess I was expecting it to be "code.InteractiveConsole". What gives?

If I then lookup the __class__ attribute of that instance I am back
full circle at the object with the unprintable name and garbage fields.
The head does seem to be valid and if it means anything to someone it's
ob_type->tp_name is "classobj". For several hours I actually wondered
why it wasn't "Type" but I guess it's just a ... subtype of Type.

I guess I should just go to bed.

Johan




More information about the Python-list mailing list