Movatterモバイル変換


[0]ホーム

URL:


Cython: C-Extensions for Python

About Cython

Cython is anoptimising static compiler for both thePython programminglanguage and the extended Cython programming language (based onPyrex).It makes writing C extensions for Python as easy as Python itself.

Cython gives you the combined power of Python and C to let you

The Cython language is a superset of thePython language thatadditionally supports callingC/C++ functions and declaringC/C++ types on variables and class attributes. This allows thecompiler to generate veryefficient C code from Cython code.The C code isgenerated once and then compiles with all majorC/C++ compilers inCPython 3.8 and all later versions.Cython 3.0.x supports Python 2.7 / 3.5 and later.We regularly run integration tests against all supported CPython versions andtheir latest in-development branches to make sure that the generated code stayswidely compatible and well adapted to each version.PyPy support ismostly usable.The latest PyPy version is always recommended here.Support for the CPython Limited API and free-threading CPython is availablein Cython 3.1 but considered experimental.

All of this makes Cython the ideal language forwrappingexternal C libraries,embedding CPython into existingapplications, and forfast C modules that speed up theexecution of Python code.

🌷️ Your donation can help the Cython project! 🌷️️

Making Cython a great programming language for you, and keeping it up to speed with the Python ecosystem and the changing requirements of its diverse user bases,takes a lot of time and dedication. To support the maintenance andfuture development of the Cython language and compiler,YOU can sponsor the work ofStefan Behnel via:

Note that PayPal takes 5 - 15% fees for small non-EUR payments, which is money that you pay without helping us. Consider signing up for a GitHub Sponsors subscription instead.

Documentation

External resources:

If you still have questions, feel free to send an email to thecython users mailing list.Aspects of the core development are discussed on thecython core developermailing list. If you are unsure which list to use, the cython users list is probably the right one to use, which has the larger audience.There is also a#cython channel on the freenode IRC servers for Cython related chats.

Download

Cython is freely available under theopen sourceApache 2.0 License.

Thelatest stable release of Cython is 3.1.4 (released 2025-09-16).Cython is available from thePyPIpackage index repository.

People

Core Developers:Stefan Behnel,Robert Bradshaw,David Woods,Matúš Valo,Lisandro Dalcín

Contributors:Marc Abramowitz,Wichert Akkerman,Martin R. Albrecht,Fedor Alekseev,Peter Alexander,Francesc Alted,Somin An,Elliott Sales de Andrade,Ivan Andrus,Michael Anselmi,Arfrever Frehtes Taifersar Arahesis,Takuro Ashie,Phil Austin,Shreyan Avigyan,William Ayd,Josh Ayers,Max Bachmann,Haoyu Bai,Grant Baillie,Nicolas Barbey,Gustavo Sverzut Barbieri,Christopher H. Barker,Richard Barnes,David Barnett,Christopher Bartak,Álvaro Abella Bascarán,Andrea Bedini,Ian Bell,Oscar Benjamin,Sebastian Berg,Jonas Bernoulli,Janek Bevendorff,Aditya Bhosale,Denis Bilenko,Bryan Bishop,Charles Blake,Chuck Blake,Max Bohnet,Guro Bokum,Bertrand Bordage,Alexey Borzenkov,Georg Brandl,Matthias Braun,Volker Braun,Nils Braun,Erik M. Bray,Erik Bray,Matthew Brett,Marcus Brinkmann,Jordan Brière,Spencer Brown,Andrew Brown,Michael Buesch,Lars Buitinck,Evgeni Burovski,Matthias Bussonnier,Corentin Cadiou,Guilherme Caminha,Josiah Carlson,Brandon Casey,Thomas A Caswell,Vladimir Cerny,Ondrej Certik,Matthew Chan,Shalabh Chaturvedi,Chia-Hsiang Cheng,Yuriy Chernyshov,Tasha Ren Chin,Eric Chlebek,David Christenson,Tzu-ping Chung,Craig Citro,James Clarke,B. Clausius,Christian Clauss,Alyssa Coghlan,Maximilien Colange,Samuel Colvin,Alexander Condello,Ludovic Cotterousse,David Cournapeau,Andreas van Cranenburgh,Armon Dadgar,Björn Dahlgren,Jeppe Dakin,Gerald Dalley,Thijs Damsma,Rajat Dash,Gabi Davar,Julien Delafontaine,Vincent Delecroix,Jeroen Demeyer,Michael V. DePalatis,Orivej Desh,Didier Deshommes,Eric Dill,Ulrich Dobramysl,Roman Donchenko,Egor Dranischnikow,Jon Dufresne,Nicolas Dumazet,Frederik Dyrmose,Ali Ebrahim,Matthew Edwards,John Ehresman,Eddie Elizondo,Sean Enck,Raffi Enficiaud,Michael Ensslin,Gerion Entrup,Yuri Escalianti,Loïc Estève,Jason Evans,Kenrick Everett,Gregory Ewing,Curtis Faith,Thomas J. Fan,Matthew Feickert,Yu Feng,Thomas Fenzl,Isuru Fernando,Ioannis Filippidis,Boris Filippov,Segev Finer,Eric Firing,Mark Florisson,Claudio Freire,Danilo Freitas,Jason Fried,Bradley M. Froehle,Gary Furnish,Syam Gadde,Martín Gaitán,Pablo Galindo,Víctor Molina García,Tim Gates,Gabriel Gellner,Julian Gethmann,Pierre Glaser,Igor Gnatenko,Prakhar Goel,Christoph Gohlke,Nathan Goldbaum,Evgeny Golyshev,Ralf Gommers,Mike Graham,Brian Granger,Robert David Grant,Olivier Grisel,Sam Gross,Christoph Groth,Moritz Groß,Charles Grunwald,Candide Guevara,Adrien Guinet,Chris Gyurgyik,Michał Górny,Hans Moritz Günther,Valentin Haenel,Yaroslav Halchenko,Luke Hamburg,Richard Hansen,Tao He,Tong He,Jonathan Helgert,Michael Helmling,Alex Henrie,Ian Henriksen,Philip Herron,Noam Hershtig,Magnus Lie Hetland,David Hirschfeld,Cheuk Ting Ho,Ewout ter Hoeven,Wieland Hoffmann,Till Hoffmann,Clemens Hofreither,Chris Hogan,Elisha Hollander,Myles Hollowed,Jackson Howard,Tomáš Hrnčiar,Miro Hrončok,Jiajun Huang,Nicolas Hug,Thomas Hunger,Eric Huss,Alex Huszagh,Julien Jerphanion,Joe Jevnik,Eric T. Johnson,Matthew Johnson,Pierre Jolivet,Andrew V. Jones,Søren Fuglede Jørgensen,Dmitry Kalinkin,Ivan Kapeykin,Igor Kaplounenko,Omer Katz,Hugo van Kemenade,Karl Kempe,Rafe Kettler,Jerome Kieffer,W. Trevor King,John Kirkham,Jim Kleckner,Thomas Kluyver,Felix Kohlgrüber,László Kiss Kollár,Mike Kolupaev,Liguo Kong,Mikhail Korobov,Sebastian Koslowski,Kacper Kowalik,Taras Kozlov,Anselm Kruis,Jakub Kulík,Patrick Kunzmann,Matěj Laitl,Ronan Lamy,Torsten Landschoff,Łukasz Langa,Eric Larson,Chris Lasher,Mathias Laurin,Sergei Lebedev,Emmanuel Leblond,Mark Lee,Antony Lee,Callie LeFave,Zhenbo Li,Thomas Li,Alex Lindsay,Molly Lloyd,Mark Lodato,Thomas Lotze,Xenia Lu,Alex Lubbock,Denis Lukianov,Pedro Marques da Luz,Dražen Lučanin,Jason Madden,Syrtis Major,Vitja Makarov,Michael Man,Yesudeep Mangalapilly,Tadeu Manoel,Nathan Manville,Gabriel de Marmiesse,Vladimir Matveev,Ben McGinnes,Bernard McKeever,Angus McMorland,Dr Alex Meakins,Brock Mendel,Petr Messner,Alexis Mignon,Mark Mikofski,Dan Miller,Volker Mische,Lawrence Mitchell,Sturla Molden,Alessandro Molina,Benedikt Morbach,Mansour Moufid,Johannes Mueller,Paul van Mulbregt,Inada Naoki,Arvind Natarajan,Nikita Nemkin,Minh Van Nguyen,Daniele Nicolodi,Lysandros Nikolaou,David Nogueira,R. Andrew Ohana,Yasuyuki Oka,Naelson Douglas C. Oliveira,Dimitri Papadopoulos Orfanos,Jay Oster,Omer Ozarslan,Joonas Paalasmaa,Andrey Paramonov,Olivier Parcollet,Nicolas Pauss,Oleksandr Pavlyk,Brent Pedersen,Mark Peek,Alexandra Pereira,Fernando Perez,Diego Elio Pettenò,Gabriel Pettier,Emmanuel Gil Peyrot,Nguyễn Gia Phong,Matti Picus,Charles Pigott,Aditya Pillai,Kryštof Pilnáček,Antoine Pitrou,Marcel Plch,Andrey Plotnikov,Pasha Podolsky,Andreas Poehlmann,Quentin Poirier,Nick Pope,Vadim Pushtaev,Martin Quarda,Vyas Ramasubramani,Jeff Ramnani,Nikolaus Rath,Martin Raum,J Robert Ray,Leo Razoumov,Peinthor Rene,Brandon Rhodes,Armin Rigo,Stefano Rivera,Min RK,Joon Ro,Clément Robert,Golden Rockefeller,Fabian Rost,Guy Rozendorn,Julian Rüth,Felix Salfelder,Loisaida Sam,Aidan Hobson Sayers,Dean Scarff,Michael Schatzow,Martin K. Scherer,Frank Schlimbach,Ralf Schmitt,Eli Schwartz,Michael Seifert,Yury Selivanov,Dag Sverre Seljebotn,Alexander Shadchin,Dmitry Shesterkin,Zaur Shibzukhov,Wenjun Si,Corbin Simpson,Alok Singhal,Kent Slaney,Kirill Smelkov,Ivan Smirnov,Nathaniel J. Smith,Kurt Smith,Sam Sneddon,Yury Sokov,Zackery Spytz,Ashwin Srinath,Martijn van Steenbergen,William Stein,Steinn Steinsen,Alexey Stepanov,Marcel Stimberg,Victor Stinner,Harmen Stoppels,Federico Stra,Andrew Straw,John Stumpo,Michael J. Sullivan,Boxiang Sun,Sviatoslav Sydorenko,Mike Taves,Julian Taylor,Dimitri Tcaciuc,Martin Teichmann,Marvin Teichmann,Maroš Telka,Mikhail Terekhov,Gregor Thalhammer,Kevin R. Thornton,Nick Timkovich,Josh Tobin,James Tocknell,Peter Todd,Erik Tollerud,Gonzalo Tornaría,Gabriele N. Tornetta,Giovanni Torres,Dmitry Trofimov,Antonio Valentino,Valentin Valls,Joris Vankerschaver,Daniele Varrazzo,Jochen Van de Velde,Jelmer Vernooij,David Vierra,Petr Viktorin,Thomas Vincent,Mathieu Virbel,Pauli Virtanen,Ruben Vorderman,Jelle van der Waa,Marius Wachtler,Philipp Wagner,Aaron M. Watson,Warren Weckesser,Tzer-jen Wei,Benjamin Weigel,peng weikang,Brian Wignall,Jakub Wilk,Alex Willmer,Steven Winfield,Willem Jan Withagen,Jouke Witteveen,Carl Witty,Scott Wolchok,Matt Wozniski,Felix Wu,Evgeny Yakimov,Yue Yang,Mads Ynddal,Charles L. Yost,Yury V. Zaytsev,Jelle Zijlstra.

Financial Contributions:Google andEnthought funded Dag Seljebotn to greatly improveCython integration with NumPy.Kurt Smith and Danilo Freitas were funded through theGoogle Summer of Code program to work on improved Fortran and C++ support respectively,and in 2010 Haoyu Bai was funded to work onPython 3 compatibility.Cython is supported byTidelift subscriptions.

Special Thanksto Greg Ewing for inventing and developing Cython's predecessorPyrexand for his valuable input in language design decisions.

Useful Links

What users have to say about Cython:

»You would expect a whole lot of organizations and people to fancy alanguage that's about as high-level as Python, yet almost as fast anddown-to-the-metal as C.

Add to that the ability to seamlessly integrate with bothyour existing C/++ codebase and your Python codebase, easily mix veryhigh level abstractions with very low-level machine access... clearwinner.« →Dun Peal on c.l.py

»You guys rock!In scikit-learn, we have decided early on to do Cython, rather than C orC++. That decision has been a clear win because the code is way moremaintainable. We have had to convince new contributors that Cython wasbetter for them, but the readability of the code, and the capacity tosupport multiple Python versions, was worth it.« →Gaël Varoquaux

»The biggest surprise (and of course this is Cython's sellingpoint) is how simple the interfacing between high level and low levelcode becomes, and the fact that it is all very robust.

It's exiciting to see that there are several active projects aroundthat attempt to speed up Python. The nice thing about Cython is thatit doesn't give you "half the speed of C" or "maybe nearly the speedof C, 3 years from now" -- it gives the real deal, -O3 C, and it worksright now.« →Fredrik Johansson

»SciPy is approximately 50% Python, 25% Fortran, 20% C, 3% Cythonand 2% C++ … The distribution of secondary programming languages in SciPyis a compromise between a powerful, performance-enhancing language thatinteracts well with Python (that is, Cython) and the usage of languages(and their libraries) that have proven reliable and performant over manydecades.

For implementing new functionality, Python is still the languageof choice. If Python performance is an issue, then we prefer the use ofCython followed by C, C++ or Fortran (in that order). The main motivationfor this is maintainability: Cython has the highest abstraction level, andmost Python developers will understand it. C is also widely known, andeasier for the current core development team to manage than C++ andespecially Fortran.« →Pauli Virtanen et al., SciPy

»Not to mention that the generated C often makes use ofperformance tricks that are too tedious or arcane to write by hand,partially motivated by scientific computing’s constant push. Andthrough all that, Cython code maintains a high level of integrationwith Python itself, right down to the stack trace and line numbers.

PayPal has certainly benefitted from their efforts throughhigh-performance Cython users like gevent, lxml, and NumPy. While ourfirst go with Cython didn’t stick in 2011, since 2015, all nativeextensions have been written and rewritten to use Cython.«→Mahmoud Hashemi

»Cython produces binaries much like C++, Go, and Rust do. Now with GitHub Actions thecross-platform build and release process can be automated for free for Open Source projects.This is an enormous opportunity to make the Python ecosystem 20-50% faster with a singlepull request.«→Grant Jenks

»I'm honestly never going back to writing C again. Cython givesme all the expressiveness of Python combined with all the performanceand close-to-the-metal-godlike-powers of C. I've been using it toimplement high-performance graph traversal and routing algorithms andto interface with C/C++ libraries, and it's been an absolute amazingproductivity boost.« →Andrew Tipton

»A general rule of thumb is that your program spends 80% ofits time running 20% of the code. Thus a good strategy for efficientcoding is to write everything, profile your code, and optimize theparts that need it. Python’s profilers are great, and Cython allowsyou to do the latter step with minimal effort.« →Hoyt Koepke

»The question was, in auto-generated code, to what extent therewere bugs there, to what extent there were bugs in the generators. Thefirst time I did this, I got lots and lots of warnings from the tool forcode generated by both SWIG and Cython [...]

Basically, everything I found Cython emitting was a false positive anda bug in my checker tool [CPyChecker].« →David Malcolm

»Basically, Cython is about 7x times faster than Boost.Python, whichastonished me.« →ChrisChou

»Using Cython allows you to just put effort into speeding up theparts of code you need to work on, and to do so without having tochange very much. This is vastly different from ditching all the codeand reimplementing it another language. It also requires you to learna pretty minimal amount of stuff. You also get to keep the niceness ofthe Python syntax which may Python coders have come toappreciate.« →Craig Macomber

»If you have a piece of Python that you need to run fast, then Iwould recommend you used Cython immediately. This means that I canexploit the beauty of Python and the speed of C together, and that’s amatch made in heaven.« →Stavros

»From 85 seconds (at the beginning of this post) down to 0.8seconds: a reduction by a factor of 100 ...thank you cython!:-)« →André Roberge

»Writing a full-on CPython module from scratch would probablyoffer better performance than Cython if you know the quirks and aredisciplined. But to someone who doesn't already drip CPython Cmodules, Cython is a godsend.

Ultimately, there's 5 commonly used ways (CPython [C-API],Boost::Python, SWIG, Cython, ctypes) to integrate C into Python, andright now you'd be crazy not to give Cython a shot, if that's yourneed. It's very easy to learn for anyone familiar with both C andPython.« →ashika

»What I loved about the Cython code is that I use a Pythonlist to manage the Vortex objects. This shows that we can use thenormal Python containers to manage objects. This is extremelyconvenient. [...]

Clearly, if you are building code from scratch and need speed,Cython is an excellent option. For this I really must congratulate theCython and Pyrex developers.« →Prabhu Ramachandran

»I wrote a script that compute a distance matrix (O^2) inPython with Numpy arrays and the same script in Cython. It took me 10minutes to figure it out how Cython works and I gained a speed up of550 times !!! Amazing« →kfrancoi

»I would like to report on a successful Cython project.Successful in the sense that it was much faster than all code writtenby my predecessors mainly because the speed scales almost linearlywith the number of cores. Also, the code is shorter and much easierto read and maintain. [...]

Making it this fast & short & readable & maintainablewould have been pretty hard without Cython.« →Alex van Houten

»At work, we’ve started using Cython with excellent success.We rewrote one particular Perl script as Cython and achieved a 600%speed improvement. As a Perl lover, this was impressive. We stillget all the benefits of Python such as rapid development and cleanobject-oriented design patterns but with the speed of C.« →Wim Kerkhoff

»The reason that I was interested in Cython was the longcalculation times I encountered while doing a multi-variableoptimization with a function evaluation that involved solving adifferential equation with scipy.integrate.odeint. By simplyreplacing the class that contained the differential equation with aCython version the calculation time dropped by a factor 5. Not badfor half a Sunday afternoons work.« →Korbinin

»I was surprised how simple it was to get it working bothunder Windows and Linux. I did not have to mess with make files orconfigure the compiles. Cython integrated well with NumPy and SciPy.This expands the programming tasks you can do with Pythonsubstantially.« →Sami Badawi

»This is why the Scipy folks keep harping about Cython – it’srapidly becoming (or has already become) the lingua franca of exposinglegacy libraries to Python. Their user base has tons of legacy codeor external libraries that they need to interface, and most of thereason Python has had such a great adoption curve in that space isbecause Numpy has made the data portion of that interface easy.Cython makes the code portion quite painless, as well.« →Peter Z. Wang

»Added an optional step of compiling fastavro with Cython.Just doing that, with no Cython specific code reduced the time ofprocessing 10K records from 2.9sec to 1.7sec. Not bad for that littlework.« →Miki Tebeka

»fastavro compiles the Python code without any specificCython code. This way on machines that do not have a compiler userscan still use fastavro.

The end result is a package that reads Avro faster than Javaand supports both Python 2 and Python 3. Using Cython and a little bitof work th[is] was achieved without too much effort.« →Miki Tebeka

»... the binding needed to be rewritten, mainly because thecurrent binding is directly written in C++ and is a maintenancenightmare. This new binding is written in Cython« →Bastien Léonard

»Code generation via Cython allows the production of smaller and more maintainable bindings, including increased compatibility with all supported Python releases without additional burden for NEST developers.«

This approach resulted in a reduction of the code footprint of around 50% and a significant increase in the cohesiveness of the code related to the Python bindings: whereas previously seven core files and 22 additional files were involved, the new approach requires merely two core files. The new implementation also removes the compile-time dependency on NumPy and provides numerous additional maintainability benefits by reducing complexity and increasing comprehensibility of the code. The re-write of the build system also resulted in a 50% reduction of code, and resolved multiple issues with its usability and robustness.«

»In conclusion, we hope that through a more widespread use of Cython, neuroscientific software developers will be able to focus their creative energy on refining their algorithms and implementing new features, instead of working to pay off the interest on the accumulating technical debt.« →Yury V. Zaytsev and Abigail Morrison

»The Cython version took about 30 minutes to write, and it runs just as fast as the C code — because, why wouldn’t it? It *is* C code, really, with just some syntactic sugar. And you don’t even have to learn or think about a foreign, complicated C API…You just, write C. Or C++ — although that’s a little more awkward. Both the Cython version and the C version are about 70x faster than the pure Python version, which uses Numpy arrays.« →Matthew Honnibal

»I love this project. Fantastic way to write Python bindings for native libs or speed up computationally intensive code without having to write C yourself.« →schmichael

»I use a lot of pyrex/cython to bind to libraries - it's so much faster to code in python. It's been a huge boon. Having used swig, hand writing wrappers, and pyrex before i can say i much prefer cython.Thank you for the hard work.« →jnazario

»I am not good with C so I mostly do pure python for my research. However, now dealing with clusters of 1000+ molecules, there was huge bottlenecks in my code.

Using cython it went from running single calculation in hours to seconds, focking nice...« →fishtickler

»Cython saves you from a great many of the gotchas [that C has].The worst you'll usually get is a lack of performance gain (at which point cython -a is your friend).Wringing out all the performance you can get can require a reasonable working knowledge of C -- but you don't have to know it that well to do pretty darn well.« →lmcinnes

»[spaCy is] written in clean but efficient Cython code, which allows usto manage both low level details and the high-level Python API in asingle codebase.« →Matthew Honnibal

»[uvloop] is written in Cython, and by the way, Cython is just amazing.It's unfortunate that it's not as wide-spread and I think it's kind-aunderappreciated what you can do in Cython. Essentially, it's asuperset of the Python language, you can strictly type it and it willcompile to C and you will have C speed. You can easily achieve it,with a syntax more similar to Python. Definitely check out Cython.« →Yury Selivanov(video@22:50)

»300.000 req/sec is a number comparable to Go's built-in web server(I'm saying this based on a rough test I made some years ago).Given that Go is designed to do exactly that, this is really impressive.My kudos to your choice to use Cython.« →beertown

»Cython is one of the best kept secrets of Python. It extends Pythonin a direction that addresses many of the shortcomings of the languageand the platform« →Ulaş Türkmen

more ...less ...


[8]ページ先頭

©2009-2025 Movatter.jp