Initializing new types
Carlos P.
cpitaar at yahoo.com.ar
Sun Jan 6 15:25:42 EST 2002
Hi!
I´m trying to figure out how to write C extensions with the
2.2 "type==class" new API. Below is an excerpt of a short program
I´m writing as a starter. The most important question is: am
I using PyType_Ready() as I should? There´s little documentation
about this function so I have taken a look at the implementation.
Also, there´s a mail from Guido in python-dev that states:
"""
Because we currently don't explicitly initialize all type object, most
types are auto-initialized on their first attribute requested from one
of their instances, by PyObject_GenericGetAttr():
"""
and then:
"""
Yes, this is a mess. We may be better off requesting that all types
are initialized explicitly;
"""
But I´m not sure if the way to explicitly initialize the type is
the one I´m following. Besides this, the code in xxsubtype.c confuses
me a little more because of the double initialization with different
base types:
"""
DL_EXPORT(void)
initxxsubtype(void)
{
PyObject *m, *d;
spamdict_type.tp_base = &PyDict_Type;
if (PyType_Ready(&spamdict_type) < 0)
return;
spamlist_type.tp_base = &PyList_Type;
if (PyType_Ready(&spamlist_type) < 0)
return;
....
}
"""
And a last thing: PEP 253 says something about PyType_InitDict(). But
I couldn´t find this function in the sources. Perhaps the PEP is a
little outdated, isn´t it?
Well, as I´ve said before, my sample code is listed below. And after
it,
an alternative one that shows what I think is not the right way (or at
least
the best way) to initialize a type. (But I´m not sure at all)
Thank you in advance,
Carlos
Sample code:
static PyTypeObject Turing_type = {
PyObject_HEAD_INIT(NULL)
0,
"Turing",
sizeof(Turing_object),
0,
(destructor)Turing_dealloc, /*tp_dealloc*/
....
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE, /* tp_flags */
Turing_doc, /* tp_doc */
....
Turing_methods, /* tp_methods */
Turing_members, /* tp_members */
....
Turing_new, /* tp_new */
....
};
DL_EXPORT(void) initturing(void) {
PyObject *d, *m;
if(PyType_Ready(&Turing_type) < 0)
return;
....
m = Py_InitModule("turing", turing_methods);
d = PyModule_GetDict(m);
....
PyDict_SetItemString(d, "Turing", (PyObject*) &Turing_type);
....
}
Alternative code:
DL_EXPORT(void) initturing(void) {
PyObject *d, *m;
// Non-constant fields initialized here:
Turing_type.ob_type = &PyType_Type;
Turing_type.tp_getattro = PyObject_GenericGetAttr;
Turing_type.tp_alloc = PyType_GenericAlloc;
Turing_type.tp_free = _PyObject_Del;
....
m = Py_InitModule("turing", turing_methods);
d = PyModule_GetDict(m);
....
PyDict_SetItemString(d, "Turing", (PyObject*) &Turing_type);
....
}
More information about the Python-list
mailing list