│ │ │
│ │ │ │ │ │
│ │ │

Porting extension types

│ │ │

The extension type structure, PyTypeObject, has seen some changes in Python 3. │ │ │ You might wish to refresh your memory with the Python documentation on this │ │ │ -(Python 2, Python 3); │ │ │ +(Python 2, Python 3); │ │ │ here we concentrate only on the differences.

│ │ │
│ │ │

Type Flags

│ │ │

The most common incompatibility in type definition involves feature flags │ │ │ -like Py_TPFLAGS_HAVE_WEAKREFS and Py_TPFLAGS_HAVE_ITER │ │ │ +like Py_TPFLAGS_HAVE_WEAKREFS and Py_TPFLAGS_HAVE_ITER │ │ │ (see Type flags reference for a full list).

│ │ │

These flags indicate capabilities that are always present in Python 3, │ │ │ so the macros are only available in Python 2. │ │ │ Most projects can simply define these to 0 in Python 3.

│ │ │

However, another use of the macros is feature checking, as in │ │ │ -PyType_HasFeature(cls, Py_TPFLAGS_HAVE_ITER). │ │ │ +PyType_HasFeature(cls, Py_TPFLAGS_HAVE_ITER). │ │ │ Defining the flags to 0 would cause that test to fail under Python 3, │ │ │ where it should instead always succeed! │ │ │ So, in these cases, the check should be done as │ │ │ (IS_PY3 || PyType_HasFeature(cls, Py_TPFLAGS_HAVE_ITER)).

│ │ │

If your project does not use PyType_HasFeature, or bypasses the check under │ │ │ Python 3 as above, you can include <py3c/tpflags.h> to define missing type │ │ │ flags as 0.

│ │ │ @@ -132,15 +132,15 @@ │ │ │

Python 3 also adds new fields at the end of PyTypeObject – but that should │ │ │ not affect initialization.

│ │ │
│ │ │
│ │ │

PyNumberMethods

│ │ │

The PyNumberMethods structure, used to implement number-like behavior │ │ │ and operators, was changed. │ │ │ -(Docs: py2, py3)

│ │ │ +(Docs: py2, py3)

│ │ │

Specifically, several members were removed:

│ │ │
│ │ │
    │ │ │
  • nb_divide (Python3 calls nb_floor_divide or nb_true_divide)

  • │ │ │
  • nb_coerce

  • │ │ │
  • nb_oct

  • │ │ │
  • nb_hex

  • │ │ │ @@ -199,15 +199,15 @@ │ │ │ You will need another #if/#else block to handle to handle both names │ │ │ of nb_nonzero, if using that.

    │ │ │
│ │ │
│ │ │
│ │ │

PyBufferProcs

│ │ │

The buffer protocol changed significantly in Python 3. │ │ │ -Kindly read the documentation, and implement │ │ │ +Kindly read the documentation, and implement │ │ │ the new buffer protocol for Python 3.

│ │ │

If you find an easier way to port buffer-aware objects, │ │ │ which other projects could benefit from, │ │ │ remember that py3c welcomes contributions.

│ │ │
│ │ │