Defining *class* methods on C code

Michael Hudson mwh at python.net
Fri Feb 6 06:24:09 EST 2004


Thomas Heller <theller at python.net> writes:

> I once knew how to do it, but I cannot find or remember it anymore:
> 
> How can I attach *class* methods to a type in C code, when I have a
> function
> 
> PyObject *func(PyObject *type, PyObject *arg);
> 
> with the METH_O calling convention?  The type is already created, I
> cannot insert it into the tp_methods array anymore.
> 
> Something like this:
> 
> class X(object):
>     pass
> 
> def func(cls, arg):
>     ....
> 
> X.func = classmethod(func)

Just stuff it into tp_dict?  You'll need to make the method object
yourself, but that's easy.

I think you probably have to hope that the name of the class method
isn't a special method name (you'd want to call
typeobject.c:update_slots then, but I don't think you can arrange for
that to happen from outside typeobject.c as all the juicy symbols are
static).

Or just stick TP_HEAPTYPE into tp_flags, use PyObject_SetAttr and take
TP_HEAPTYPE out again (that's very sick, though).

Cheers,
mwh

-- 
  > Well, as an American citizen I hope that the EU tells the MPAA 
  > and RIAA to shove it where the Sun don't shine.
  Actually they already did. Only first they bent over and dropped
  their trousers.      -- Shmuel (Seymour J.) Metz & Toni Lassila, asr



More information about the Python-list mailing list