C extension type gives type error in power operator

Thomas Heller theller at python.net
Thu Nov 20 10:43:42 EST 2008


Paul Moore schrieb:
> I'm trying to implement an extension type with a power operator. The
> operator is unusual in that I want to allow my objects to be raised to
> an integer power:
> 
>    p = Pattern()
>    p3 = p ** 3
> 
> I've implemented the code for a nb_power slot, it converts the "other"
> argument to a C long using PyInt_AsLong().
> 
> static PyObject *
> Pattern_pow (PyObject *self, PyObject *other, PyObject *modulo)
> {
>     long n = PyInt_AsLong(other);
>     ...
>     /* Ignore modulo argument - not meaningful */
> 
>     if (n == -1 && PyErr_Occurred())
>         return NULL;
> ...
> }
> 
> However, when I try to use the operator, I get the following error:
> TypeError: unsupported operand type(s) for ** or pow():
> '_ppeg.Pattern' and 'int'

Try to set Py_TPFLAGS_CHECKTYPES in your extension type (in the tp_flags slot).

from object.h:
  /* PyNumberMethods do their own coercion */
  #define Py_TPFLAGS_CHECKTYPES (1L<<4)

> I'm not sure where this error is coming from, as I don't have any type
> checks in my code. Is there something else I should add to allow mixed-
> type operations? (This is Python 2.5, if it matters).
> 
> Oh, and is there a good reference for writing C extensions for Python
> anywhere? The manuals aren't bad, but I keep hitting empty sections
> (e.g., 10.5 Number Object Structures).

I normally look into the newest python reference manual, even if I'm
programming for older versions.  But sometimes you have to took into
the header files, too.

Thomas



More information about the Python-list mailing list