Skip to content

Instantly share code, notes, and snippets.

@kemingy
Last active April 1, 2020 02:54
Show Gist options
  • Save kemingy/224008c22bbc0c88f529ceebab8b39d6 to your computer and use it in GitHub Desktop.
Save kemingy/224008c22bbc0c88f529ceebab8b39d6 to your computer and use it in GitHub Desktop.
Cython notes

Install

pip install cython

Build

  • setuptools
    • setup.py
      from setuptools import setup
      from Cython.Build import cythonize
      
      setup(
          name='Hello world app',
          ext_modules=cythonize(
              ['hello.pyx'],
              annotate=True, # enable generation of the HTML annotation files
              compiler_directives={
                  'language_level': 3, # Python3
              }
          ),
          zip_safe=False,
      )
    • build: python setup.py build_ext --inplace
    • build files(with analysis will generate HTML files): cython -a hello.pyx
  • Jupyter Notebook
    • load: %load_ext Cython
    • compile: %%cython (with analysis %%cython --annotate)

Exceptions

cdef double func(double x) except? -2:
    return x ** 2 - x
  • except -1: whenever returns -1, an exception will be assumed to have occurred
  • except? -1: whenever returns -1, it will check with PyErr_Occurred()
  • except *: always check with PyErr_Occurred() (external C++ except +)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment