Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

c

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
like image 586
Raphael Ahrens Avatar asked Sep 10 '12 09:09

Raphael Ahrens


People also ask

What is Python C API?

The Python/C API allows for compiled pieces of code to be called from Python programs or executed within the CPython interpreter. This process of producing compiled code for use by CPython is generally known as "extending" Python and the compiled pieces of code to be used are known as "extension modules".

What is a Python extension module?

¶ A CPython extension module is a module which can be imported and used from within Python which is written in another language. Extension modules are almost always written in C, and sometimes in C++, because CPython provides an API for working with Python objects targeted at C.

Are Python modules written in C?

Most of the Python Libraries are written in the C programming language.


1 Answers

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
like image 195
Janne Karila Avatar answered Oct 24 '22 04:10

Janne Karila