Computing in SCienCe & engineering This arTicle has been peer-reviewed. 31

2016

S c i e n t i f i c P y t h o n Cython is a Python language extension that allows explicit type declarations and is compiled directly to C. As such, it addresses Python’s large overhead for numerical loops and the difficulty of efficiently using existing C and Fortran code, which Cython can interact with natively. Cython: The Best of Both Worlds P ython’s success as a platform for sci-entific computing to date is primarily due to two factors. First, Python tends to be readable and concise, leading to a rapid development cycle. Second, Python provides access to its internals from C via the Python/C API. This makes it possible to inter-face with existing C, C++, and Fortran code, as well as to write critical sections in C when speed is essential. Although Python is fast enough for many tasks, low-level computational code written in Python tends to be slow, largely due to Python’s extremely dynamic nature. In particular, low-level compu-tational loops are simply infeasible. Although NumPy eliminates the need for many such loops,1 there will always be computations that can be expressed well only through looping constructs. Cython aims to be a good companion to NumPy in such cases. Given the magnitude of existing, well-tested code in Fortran and C, rewriting it in Python would waste valuable resources. A big part of Python’s role in science is its ability to couple existing components instead of reinventing the wheel. For example, the Python-specific SciPy library contains more than 200,000 lines of C++, 60,000 lines of C, and 75,000 lines of Fortran, compared to about 70,000 lines of Python code. Wrapping existing code has traditionally been the domain of Python experts because the Python/C API has a high learning curve. Although you can use such wrappers without ever knowing their in-ternals, this approach draws a sharp line between users (using Python) and developers (using C with the Python/C API). Cython solves both of these problems by com-piling Python code (with some extensions) di-rectly to C, which is then compiled and linked against Python and ready to use from the inter-preter. Because it uses C types, Cython makes it possible to embed numerical loops, running at C speed, directly in Python code. Cython also significantly lowers the learning curve for call-

Read the paper · More papers on PaperTik