Book Image

Learning Cython Programming

By : Philip Herron
Book Image

Learning Cython Programming

By: Philip Herron

Overview of this book

<p>Cython is a very powerful combination of Python and C. Using Cython, you can write Python code that calls back and forth from and to C or C++ code natively at any point. It is a language with extra syntax allowing for optional static type declarations. It is also a very popular language as it can be used for multicore programming.</p> <p>Learning Cython Programming will provide you with a detailed guide to extending your native applications in pure Python; imagine embedding a twisted web server into your native application with pure Python code. You will also learn how to get your new applications up and running by reusing Python’s extensive libraries such as Logging and Config Parser to name a few.</p> <p>With Learning Cython Programming, you will learn that writing your own Python module in C from scratch is not only hard, but is also unsafe. Cython will automatically handle all type-conversion issues as well as garbage collection on your code. You can also still write all your code in Python but have it compiled and called directly in C as if it was just another function or data.</p> <p>This book also demonstrates how you can take the open source project Tmux and extend it to add new commands directly in pure Python. With this book, you will learn everything you need to know to get up and running with Cython and how you can reuse examples in a practical way.</p>
Table of Contents (13 chapters)

Compile time


At compile time, just like in C/C++, we have the C-preprocessor to make some decisions on what gets compiled, mostly from conditionals, defines, and a mixture of both. In Cython, we can replicate some of this behavior using IF, ELIF, ELSE, and DEF. This is demonstrated as an example in the following code line:

DEF myConstant = "hello cython"

We also have access to os.uname as predefined constants from the Cython compiler:

  • UNAME_SYSNAME

  • UNAME_NODENAME

  • UNAME_RELEASE

  • UNAME_VERSION

  • UNAME_MACHINE

We can also run conditional expressions against these, such as:

IF UNAME_SYSNAME == "Windows":
    include "windows.pyx"
ELSE:
    include "unix.pyx"

You also have ELIF to use in conditional expressions. If you compare something like this against some of your headers in C programs, you will see how you can replicate basic C-preprocessor behavior in Cython. This gives you a quick idea of how you could replicate C-preprocessor usage in your headers.