Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How do I call super() in c extention ?

11 views
Skip to first unread message

umedoblock

unread,
Jan 26, 2012, 9:03:57 PM1/26/12
to pytho...@python.org
Hi, nice to meet you, everyone.
I'm umedoblock.

I'd like to call super() in c extension.
I'd like to rewrite class Baa as c extension.
Please see below code.
Now, I can make super object.

But I cannot understand how to use super_init(), super_descr_get() and
super_getattro().

Please please help me...

------------------------------------------------------------
baa.py

class Baa(object):
def __init__(self):
print('call __init__() in Baa.')
def sample(self):
print('call sample() in Baa.')
class Foo(Baa):
def __init__(self):
print('call __init__() in Foo.')
super().sample()
super().__init__()
class Baz(Foo):
def __init__(self):
print('call __init__() in Baz.')
super().__init__()
--
pyfoo.c

static int
Foo_init(FooObject *self, PyObject *args, PyObject *kwds)
{
int ret = 0;
PyTypeObject *super_type = &PySuper_Type;
PyObject *super_obj;
PyObject *empty_tuple;

super_obj = super_type->tp_alloc(super_type, 0);

empty_tuple = Py_BuildValue("()");
ret = super_type->tp_init(super_obj, empty_tuple, NULL);

fprintf(stderr, "super_obj = %p\n", super_obj);
PyObject_Print((PyObject *)super_obj, stderr, 0); fprintf(stderr,
"\n\n");
fprintf(stderr, "super_type->tp_init(super_obj=%p, empty_tuple=%p,
NULL)=%d\n", super_obj, empty_tuple, ret);

return 0;
}

PyMODINIT_FUNC
PyInit__foo(void)
{
PyObject *m;
PyObject *import_baa = NULL, *Baa = NULL;
PyObject *Baa_str;

import_baa = PyImport_ImportModule("baa");
Baa_str = Py_BuildValue("s", "Baa");
Baa = PyObject_GetAttr(import_baa, Baa_str);
Foo_Type.tp_base = (struct _typeobject *)Baa;
Py_INCREF(Foo_Type.tp_base);

Foo_Type.tp_new = Foo_new;
if (PyType_Ready(&Foo_Type) < 0)
return NULL;
Py_INCREF(&Foo_Type);

m = PyModule_Create(&Foo_module);
if (m == NULL)
return NULL;
PyModule_AddObject(m, "Foo", (PyObject *)&Foo_Type);

PyModule_AddStringConstant(m, "CONST", "C_EXTENSION");

return m;
}

Stefan Behnel

unread,
Jan 27, 2012, 2:48:06 AM1/27/12
to pytho...@python.org
umedoblock, 27.01.2012 03:03:
> I'd like to call super() in c extension.
> I'd like to rewrite class Baa as c extension.

Have you considered using Cython for this? It will allow you to do exactly
that with only minor changes to your Python code (if any). And it's quite
likely that the C code that it generates from your Python code will be more
efficient than what you'd write manually. Certainly more readable and
maintainable.

Stefan

YASUDA Hideyuki

unread,
Jan 28, 2012, 2:17:38 AM1/28/12
to pytho...@python.org
> Have you considered using Cython for this?

No. I hadn't known Cython.
Now, I'll try to use Cython.

thanks.

umedoblock
0 new messages