Book Image

Learning Cython Programming (Second Edition) - Second Edition

By : Philip Herron
Book Image

Learning Cython Programming (Second Edition) - Second Edition

By: Philip Herron

Overview of this book

Cython is a hybrid programming language used to write C extensions for Python language. Combining the practicality of Python and speed and ease of the C language it’s an exciting language worth learning if you want to build fast applications with ease. This new edition of Learning Cython Programming shows you how to get started, taking you through the fundamentals so you can begin to experience its unique powers. You’ll find out how to get set up, before exploring the relationship between Python and Cython. You’ll also look at debugging Cython, before moving on to C++ constructs, Caveat on C++ usage, Python threading and GIL in Cython. Finally, you’ll learn object initialization and compile time, and gain a deeper insight into Python 3, which will help you not only become a confident Cython developer, but a much more fluent Python developer too.
Table of Contents (14 chapters)
Learning Cython Programming Second Edition
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface
Index

Python garbage collector


When wrapping up native structs, for example, it can be very tempting to follow standard C/C++ idioms and require the Python programmer to call, allocate, and release manually on different objects. This is very tedious and not very Pythonic. Cython allows us to create cdef classes, which have extra hooks for initialization and deallocation that we can use to control all memory management of structs. These hooks are triggered automatically by the Python garbage collector, making everything nice and simple. Consider the following simple struct:

typedef struct data {
  int value;
} data_t;

We can then write the Cython declaration of the C struct into PyData.pxd as follows:

cdef extern from "Data.h":
    struct data:
        int value
    ctypedef data data_t

Now that we have defined the struct, we can wrap up the struct into a class:

cimport PyData

cdef class Data(object):
    cdef PyData.data_t * _nativeData
    …

Wrapping up data into a class like this will require us...