O'Reilly logo

Python High Performance Programming by Gabriele Lanaro

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding static types

In Python, variables have an associated type that can change during the execution. While this feature is desirable, as it makes the language more flexible, the interpreter needs to do type-checks and method look-ups to correctly handle operations between variables—an extra step that introduces a significant overhead. Cython extends the Python language with static type declarations; in this way it can generate efficient C code by avoiding the Python interpreter.

The main way to declare data types in Cython is by using cdef statements. The cdef keyword can be used in multiple contexts: to declare variables, functions, and extension types (cdef classes).

Variables

In Cython you can declare the type of a variable by prepending the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required