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

Cython and C++


Cython, above all binding generators, works with C++ the most seamlessly. C++ has some complexity when writing bindings for it, such as calling conventions, templates, and classes. I find this exception handling to be a shining feature of Cython, and we will look at the examples of each.

Namespaces

I am introducing namespaces first because Cython uses namespaces as a way to reference C++ code within your module. Consider this C++ header with the following namespace:

#ifndef __MY_HEADER_H__
#define __MY_HEADER_H__

namespace mynamespace {
….
}

#endif //__MY_HEADER_H__

You will wrap this with the cdef extern declaration:

cdef extern from "header.h" namespace "mynamespace":

You can now address it in Cython as you normally would do for a module:

import cythonfile
cythonfile.mynamespace.attribute

It really feels like a Python module simply by using a namespace.

Classes

I would take a guess that most of your C++ code revolves around using classes. Being an object-oriented language...