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
About the Author
About the Reviewer

Cython caveats

There are some caveats worth noting while mixing C and the Python code when it comes to Cython. It's a good idea to refer to these when building something to be production ready.

Type checking

You may have noticed that in the previous code examples, we were able to cast the void * pointer from malloc to our extension types using malloc. Cython supports some more advanced type checking as follows:

char * buf = <char *> malloc (sizeof (...))

In basic type casting, Cython supports <type?> for type checking:

char * buf  = <char *?> malloc (...)

This will do some type checking and throw an error if the type that is being cast is not a subclass of char *. So, in this case, it will pass; however, if you were to do the following:

cdef class A:
cdef class B (A):

def myfunc ():
    cdef A class1 = A ()
    cdef B class2 = B ()
    cdef B x = <B?> class1

This will return an error (at runtime):

Traceback (most recent call last):
  File "", line...