Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning Cython Programming (Second Edition)
Learning Cython Programming (Second Edition)

Learning Cython Programming (Second Edition): Expand your existing legacy applications in C using Python , Second Edition

eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learning Cython Programming (Second Edition)

Chapter 1. Cython Won't Bite

Cython is much more than a programming language. Its origin can be traced to SAGE, the mathematics software package, where it is used to increase the performance of mathematical computations such as those involving matrices. More generally, I tend to consider Cython as an alternative to SWIG to generate really good Python bindings to native code.

Language bindings have been around for years, and SWIG was one of the first and best tools to generate bindings for multitudes of languages. Cython generates bindings for Python code only, and this single purpose approach means it generates the best Python bindings you can get outside of doing it all manually, which should be attempted only if you're a Python core developer.

For me, taking control of legacy software by generating language bindings is a great way to reuse any software package. Consider a legacy application written in C/C++. Adding advanced modern features such as a web server for a dashboard or message bus is not a trivial thing to do. More importantly, Python comes with thousands of packages that have been developed, tested, and used by people for a long time that can do exactly that. Wouldn't it be great to take advantage of all of this code? With Cython, we can do exactly this, and I will demonstrate approaches with plenty of example codes along the way.

This first chapter will be dedicated to the core concepts on using Cython, including compilation, and should provide a solid reference and introduction for all the Cython core concepts.

In this first chapter, we will cover:

  • Installing Cython
  • Getting started - Hello World
  • Using distutils with Cython
  • Calling C functions from Python
  • Type conversion

Installing Cython

Since Cython is a programming language, we must install its respective compiler, which just so happens to be the aptly named Cython.

There are many different ways to install Cython. The preferred one would be to use pip:

$ pip install Cython

This should work on both Linux and Mac. Alternatively, you can use your Linux distribution's package manager to install Cython:

$ yum install cython     # will work on Fedora and Centos
$ apt-get install cython # will work on Debian based systems.

For Windows, although there are a plethora of options available, following this wiki is the safest option to stay up-to-date: http://wiki.cython.org/InstallingOnWindows.

Emacs mode

There is an emacs mode available for Cython. Although the syntax is nearly the same as Python, there are differences that conflict in simply using Python-mode. You can grab cython-mode.el from the Cython source code (inside the Tools directory.) The preferred way of installing packages to emacs would be to use a package repository like MELPA:

To add the package repository to emacs, open your ~/.emacs configuration file and add:

(when (>= emacs-major-version 24)
  (require 'package)
  (add-to-list
   'package-archives
   '("melpa" . "http://melpa.org/packages/")
   t)
  (package-initialize))

Once you add this and reload your configuration to install the Cython mode, you can simply run:

'M-x package-install RET cython-mode'

Once this is installed, you can activate the mode by adding this into your emacs config file:

(require 'cython-mode)

You can activate the mode manually at any time with:

'M-x cython-mode RET'

Getting the code examples

Throughout this book, I intend to show real examples that are easy to digest in order to help you get a feel of the different things you can achieve with Cython. To access and download the code used, please clone this repository:

$ git clone git://github.com/redbrain/cython-book.git

Getting started – Hello World

As you will see when running the Hello World program, Cython generates native Python modules. Therefore, running any Cython code, you will reference it via a module import in Python. Let's build the module:

$ cd cython-book/chapter1/helloworld
$ make

You should now have created helloworld.so! This is a Cython module of the same name as the Cython source code file. While in the same directory of the shared object module, you can invoke this code by running a respective Python import:

$ python
Python 2.7.3 (default, Aug  1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import helloworld
Hello World from cython!

As you can see by opening helloworld.pyx, it looks just like a normal Python Hello World application, but as previously stated, Cython generates modules. These modules need a name so that they can be correctly imported by the Python runtime. The Cython compiler simply uses the name of the source code file. It then requires us to compile this to the same shared object name.

Overall, Cython source code files have the .pyx,.pxd, and .pxi extensions. For now, all we care about are the .pyx files; the others are for cimports and includes respectively within a .pyx module file.

The following screenshot depicts the compilation flow required to have a callable native Python module:

Getting started – Hello World

I wrote a basic makefile so that you can simply run make to compile these examples. Here's the code to do this manually:

$ cython helloworld.pyx
$ gcc/clang -g -O2 -fpic `python-config --cflags` -c helloworld.c -o helloworld.o
$ gcc/clang -shared -o helloworld.so helloworld.o `python-config –libs`

Using distutils with Cython

You can also compile this HelloWorld example module using Python distutils and cythonize. Open the setup.py along side the Makefile and you can see the alternate way to compile Cython modules:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("helloworld.pyx")
)

Using the cythonize function as part of the ext_modules section will build any specified Cython source into an installable Python module. This will compile helloworld.pyx into the same shared library. This provides the Python practice to distribute native modules as part of distutils.

Calling C functions from Python

We should be careful for clarity when talking about Python and Cython since the syntax is so similar. Let's wrap a simple AddFunction in C and make it callable from Python.

First, open a file called AddFunction.c, and write a simple function in it:

#include <stdio.h>

int AddFunction(int a, int b) {
    printf("look we are within your c code!\n");
    return a + b;
}

This is the C code that we will call—just a simple function to add two integers. Now, let's get Python to call it. Open a file called AddFunction.h, wherein we will declare our prototype:

#ifndef __ADDFUNCTION_H__
#define __ADDFUNCTION_H__

extern int AddFunction (int, int);

#endif //__ADDFUNCTION_H__

We need this so that Cython can see the prototype for the function we want to call. In practice, you will already have your headers in your own project with your prototypes and declarations already available.

Open a file called AddFunction.pyx, and insert the following code in it:

cdef extern from "AddFunction.h":
    cdef int AddFunction(int, int)

Here, we have to declare which code we want to call. The cdef is a keyword signifying that this is from the C code that will be linked in. Now, we need a Python entry point:

def Add(a, b):
     return AddFunction(a, b)

This Add function is a Python callable inside a PyAddFunction module this acts as a wrapper for Python code to be able to call directly into the C code. Again, I have provided a handy makefile to produce the module:

$ cd cython-book/chapter1/ownmodule
$ make
cython -2 PyAddFunction.pyx
gcc -g -O2 -fpic -c PyAddFunction.c -o PyAddFunction.o `python-config --includes`
gcc -g -O2 -fpic -c AddFunction.c -o AddFunction.o
gcc -g -O2 -shared -o PyAddFunction.so AddFunction.o PyAddFunction.o `python-config --libs`

Notice that AddFunction.c is compiled into the same PyAddFunction.so shared object. Now, let's call this AddFunction and check to see if C can add numbers correctly:

$ python
>>> from PyAddFunction import Add
>>> Add(1,2)
look we are within your c code!!
3

Notice that the print statement inside the AddFunction and the final result are printed correctly. Therefore, we know that the control hit the C code and did the calculation in C, and not inside the Python runtime. This is a revelation of what is possible. Python can be cited to be slow in some circumstances. Using this technique makes it possible for Python code to bypass its own runtime and to run in an unsafe context, which is unrestricted by the Python runtime which is much faster.

Type conversion in Cython

Notice that we had to declare a prototype inside the Cython source code PyAddFunction.pyx:

cdef extern from "AddFunction.h":
    cdef int AddFunction(int, int)

It lets the compiler know that there is a function called AddFunction and it takes two ints and returns an int. This is all the information the compiler needs to know beside the host and target operating system's calling convention to call this function safely. Then, we created the Python entry point, which is a Python callable that takes two parameters:

def Add(a, b):
     return AddFunction(a, b)

Inside this entry point, it simply returned the native AddFunction and passed the two Python objects as parameters. This is what makes Cython so powerful. Here, the Cython compiler must inspect the function call and generate code to safely try and convert these Python objects to native C integers. This becomes difficult when precision is taken into account as well as potential overflow, which just so happens to be a major use case since it handles everything so well. Also, remember that this function returns an integer, and Cython also generates code to convert the integer return into a valid Python object.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Summary

Overall, we installed the Cython compiler, ran the Hello World example, and took into consideration that we need to compile all code into native shared objects. We also saw how to wrap native C code to make it callable from Python. We have also seen the implicit type conversion which Cython does for us to make calling C work. In the next chapter, we will delve deeper into Cython programming with discussion on how to make Python code callable from C and manipulate native C data structures from Cython.

Left arrow icon Right arrow icon

Key benefits

  • Learn how to extend C applications with pure Python code
  • Get more from Python – you’ll not only learn Cython, you’ll also unlock a greater understanding of how to harness Python
  • Packed with tips and tricks that make Cython look easy, dive into this accessible programming guide and find out what happens when you bring C and Python together!

Description

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.

Who is this book for?

This book is for developers who are familiar with the basics of C and Python programming and wish to learn Cython programming to extend their applications.

What you will learn

  • Reuse Python logging in C
  • Make an IRC bot out of your C application
  • Extend an application so you have a web server for rest calls
  • Practice Cython against your C++ code
  • Discover tricks to work with Python ConfigParser in C
  • Create Python bindings for native libraries
  • Find out about threading and concurrency related to GIL
  • Expand Terminal Multiplexer Tmux with Cython
Estimated delivery fee Deliver to Italy

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 22, 2016
Length: 110 pages
Edition : 2nd
Language : English
ISBN-13 : 9781783551675
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Italy

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Feb 22, 2016
Length: 110 pages
Edition : 2nd
Language : English
ISBN-13 : 9781783551675
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 95.97
Modular Programming with Python
€32.99
Learning Cython Programming (Second Edition)
€29.99
Learning Python Design Patterns - Second Edition
€32.99
Total 95.97 Stars icon
Banner background image

Table of Contents

7 Chapters
1. Cython Won't Bite Chevron down icon Chevron up icon
2. Understanding Cython Chevron down icon Chevron up icon
3. Extending Applications Chevron down icon Chevron up icon
4. Debugging Cython Chevron down icon Chevron up icon
5. Advanced Cython Chevron down icon Chevron up icon
6. Further Reading Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Todd Leonhardt Dec 25, 2016
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
For the vast majority of people looking to learn Cython, this book is absolutely horrible. It is poorly written and does a truly bad job of covering the basics of Python. If you want to learn Cython, there are vastly better resources: the online docs at cython.org are excellent, as is the book "Cython" by Kurt Smith. There is also a good 3.5 hour training video on Youtube from SciPy 2015.However, this book does have a few hidden gems for someone who is already a seasoned C, Python, and Cython developer. It does have a couple excellent examples of how to get C applications to easily call into Python code by using Cython.The book really should have a different title. As a "Learning Cython Programming" book, it deserves 1 star. But as a "Learning how to easily call Python code from a C application by using Cython" book, it would deserve 3 or 4 stars. But I would estimate that less than 5% of the people interested in learning Cython fish to learn it for this purpose - probably about 80% want to learn it to optimize existing Python code and maybe 15 to 20% want to learn it to wrap existing C/C++ code so it can be called from Python.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela