{"id":324,"date":"2020-12-24T15:09:24","date_gmt":"2020-12-24T23:09:24","guid":{"rendered":"https:\/\/nramkumar.org\/tech\/?p=324"},"modified":"2020-12-26T16:09:36","modified_gmt":"2020-12-27T00:09:36","slug":"a-brief-and-practical-introduction-to-cython","status":"publish","type":"post","link":"https:\/\/nramkumar.org\/tech\/blog\/2020\/12\/24\/a-brief-and-practical-introduction-to-cython\/","title":{"rendered":"A Brief and Practical Introduction to Cython"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">What is Cython and what do I use it for?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Cython is an extension of the Python programming language that enables C\/C++ and Python interop as well as speeding up Python code. There are three main use cases for Cython:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Exposing functionality written in Python to native code written in C\/C++ \u2013 this use case IMO is quite rare. But it is something that Cython enables.<\/li><li>Exposing functionality written in C\/C++ to Python code \u2013 this is very useful when we have native libraries in C\/C++ that do not have Python bindings but we want to leverage their functionality in Python.<\/li><li>A higher level language (Python + some extensions) that allows you to produce efficient native code and accessible via Python \u2013 basically, write Python code but execute at close to native code speed. This is very useful as you can leverage the ease of use and higher level abstractions provided by Python but get the efficiency of native code during execution.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How does Cython work?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Cython allows you to write Python like code, generates native C&nbsp; (or C++) code from this and compiles it into a Python extension module that can be imported and used in Python like any other Python module. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here\u2019s a simple example \u2013 start by creating <code>CythonHelloWorld.pyx<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def hello_world():\n    print('Hello, World!')<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, we create <code>setup.py<\/code> to enable distutils to generate the C file and build the extension from this Cython file:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from distutils.core import setup\nfrom distutils.extension import Extension\nimport sys\n\nUSE_CYTHON = False\nif '--use-cython' in sys.argv:\n    USE_CYTHON = True\n    sys.argv.remove('--use-cython')\n\next = '.pyx' if USE_CYTHON else '.c'\nextensions = &#91;\n    Extension(\n        name='helloworld',\n        sources=&#91;'CythonHelloWorld'+ext],\n        language='c',\n    )\n]\n\nif USE_CYTHON:\n    from Cython.Build import cythonize\n    extensions = cythonize(extensions)\n\nsetup(\n    name='helloworld',\n    ext_modules = extensions\n)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The above <code>setup.py <\/code>file will generate <code>CythonHelloWorld.c<\/code> and then build it into a <code>helloworld<\/code> Python extension module &#8211; the extra complexity here is for distributing this module outside the development environment where the recommended practice is to include the generate <code>.c<\/code> or <code>.cpp<\/code> file instead of assuming the presence of Cython and having the user generate the file. Use the following command to generate the .c file, compile it into a Python extension and install it in-place:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python setup.py build_ext --inplace --use-cython<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now you can test this by creating <code>run.py<\/code> which uses the new extension module:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import helloworld\n\nhelloworld.hello_world()\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And finally, running the above run.py to verify that it works:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python run.py\nHello, World!<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If all you are looking for is using Cython to create faster code that is written in Python like syntax, this is essentially all you need. We will look at the interesting use case of generating a Python accessible wrapper for a C library in a future post.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is Cython and what do I use it for? Cython is an extension of the Python programming language that enables C\/C++ and Python interop as well as speeding up Python code. There are three main use cases for Cython: Exposing functionality written in Python to native code written in C\/C++ \u2013 this use case&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[96],"tags":[97,98],"class_list":["post-324","post","type-post","status-publish","format-standard","hentry","category-python","tag-development","tag-programming"],"_links":{"self":[{"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/posts\/324","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/comments?post=324"}],"version-history":[{"count":5,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/posts\/324\/revisions"}],"predecessor-version":[{"id":336,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/posts\/324\/revisions\/336"}],"wp:attachment":[{"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/media?parent=324"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/categories?post=324"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nramkumar.org\/tech\/wp-json\/wp\/v2\/tags?post=324"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}