Extensions

18_extensions

Basic Cython Extension

First we need to make sure Cython is installed.

$ pip install Cython
...

Create three files:

  • KnuthBShuffle.pyx
  • setup.py
  • README.md
# File: KnuthBShuffle.pyx
from random import randint

def shuffle(array):
    """ Knuth B Shuffle Algorithm
    Destructive, in-place shuffle.
    @param array :: mutable sequence of values.
    @return :: None """
    size = len(array) - 1
    for i in reversed(range(size)):
        j = randint(i, size)
        array[i], array[j] = array[j], array[i]
# File: setup.py
from setuptools import setup, Extension
from Cython.Build import cythonize

with open("README.md", "r") as file:
    long_description = file.read()

setup(
    name="KnuthBShuffle",
    ext_modules=cythonize(
        Extension(
            name="KnuthBShuffle",
            sources=["KnuthBShuffle.pyx"],
        ),
        compiler_directives={
            'embedsignature': True,
            'language_level': 3,
        },
    ),
    author="One Awesome Developer",
    author_email="you@yourdomain.com",
    requires=["Cython"],
    version="0.0.1",
    description="Knuth B Shuffle Algorithm",
    long_description=long_description,
    long_description_content_type="text/markdown",
    classifiers=["Development Status :: 1 - Planning"],
    keywords=["Shuffle", "Knuth B"],
    python_requires='>=3.6',
)
# File: README.md

Knuth B Shuffle Algorithm: Destructive, in-place shuffle.

Reverse Order Random Swap Backwards - a cache friendly shuffle.
...

Installation & Usage

Browse to the directory holding the files. Open a terminal and type the following:

$ pip install .
$ python3
>>> from KnuthBShuffle import shuffle
>>> arr = list(range(10)
>>> shuffle(arr)
>>> print(arr)
[1, 0, 8, 6, 9, 5, 4, 7, 2, 3]
>>>
>>> help(shuffle)
Help on built-in function shuffle in module KnuthBShuffle:

shuffle(...)
    shuffle(array)
    Knuth B Shuffle Algorithm
       Destructive, in-place shuffle.
       @param array :: mutable sequence of values.
       @return :: None