Skip to content
Advertisement

A full and minimal example for a class (not method) with Python C Extension?

Everywhere, I can easily find an example about writing a method with Python C Extensions and use it in Python. Like this one: Python 3 extension example

JavaScript

How to do write a hello word full featured Python class (not just a module method)?

I think this How to wrap a C++ object using pure Python Extension API (python3)? question has an example, but it does not seem minimal as he is using (or wrapping?) C++ classes on it.

For example:

JavaScript

What is the equivalent of this Python class example with C Extensions?

I would use it like this:

JavaScript

My goal is to write a class fully written in C for performance (all other classes in my project will be in Python, except this one). I am not looking for portability as using ctypes, neither black boxes as using Boost.Python or SWIG. Just a high-performance class purely written with Python C Extensions.

After I got this Hello word working, I can figure my self out within Python Extensive documentation:

  1. https://docs.python.org/3/c-api/
  2. https://docs.python.org/3/extending/extending.html

Advertisement

Answer

See also: Python instance method in C

Create the file called MANIFEST.in

JavaScript

Create the file called setup.py

JavaScript

Create the file called source/custom.cpp

JavaScript

Then, to compile it and install you can run either:

JavaScript

As side note from this question How to use setuptools packages and ext_modules with the same name? do not mix on the same project *.py files and Python C Extensions, i.e., use only purely C/C++, building Python C Extensions without adding packages = [ 'package_name' ] entries because they cause the Python C Extensions code run 30%, i.e., if the program would take 7 seconds to run, now with *.py files, it will take 11 seconds.

References:

  1. https://docs.python.org/3/extending/newtypes_tutorial.html#supporting-cyclic-garbage-collection
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement