Raphael Ahrens
Raphael Ahrens

Reputation: 992

How to check the version of the python API at compile time from a C extension module?

I am writing a python module in C. The module needs to be compiled for python version 2.4, 2.5, 2.6 and 2.7.

Now I ran in to the problem that in python 2.5 they defined Py_ssize_t for the size of lists, but in 2.4 they just used int.

So my question is: Is there an easy way to check if I'm using the API of version 2.4 or 2.5 at compile time so I can write a little macro?

e.g:

#if PY_MINOR < 5
typedef int Py_ssize_t;
#endif

Upvotes: 16

Views: 6813

Answers (3)

Khoa Le
Khoa Le

Reputation: 15

Just do something similar to this.

import sys
if sys.version_info < (2, 4): //do something, typedef what you need
else // so on

Upvotes: -7

Janne Karila
Janne Karila

Reputation: 25197

Yes, patchlevel.h in the Python include dir defines what you are looking for:

#define PY_MAJOR_VERSION    2
#define PY_MINOR_VERSION    5
#define PY_MICRO_VERSION    2

Upvotes: 15

iMom0
iMom0

Reputation: 12911

I think what you need is PY_VERSION_HEX

there is one line in c code generated by cython

PY_VERSION_HEX < 0x02040000

#ifndef Py_PYTHON_H
  #error Python headers needed to compile C extensions, please install development version of Python.
#elif PY_VERSION_HEX < 0x02040000
  #error Cython requires Python 2.4+.
#else

Upvotes: 13

Related Questions