Declaring built-in Python types


In [1]:
%load_ext cython

1) Type safety


In [2]:
%%cython

cpdef set f(list x):
    """ Convert a list to a set. """
    return set(x)

In [3]:
# This is a list: good!
data = [1,2,3]
print(f(data))


{1, 2, 3}

In [4]:
# Hey, this isn't a list!
data = (1,2,3)
print(f(data))


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-fcaa1119ef68> in <module>()
      1 # Hey, this isn't a list!
      2 data = (1,2,3)
----> 3 print(f(data))

TypeError: Argument 'x' has incorrect type (expected list, got tuple)

Lock inner variables to types


In [5]:
%%cython

def f(x):
    cdef list output
    output = x
    return output

In [6]:
# Succeeds if we really did give a list
f([])


Out[6]:
[]

In [7]:
# Fails if we don't
f(42)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-64257a0f1a52> in <module>()
      1 # Fails if we don't
----> 2 f(42)

_cython_magic_9e64b76046e46a8c647811a3689ce26a.pyx in _cython_magic_9e64b76046e46a8c647811a3689ce26a.f (/Users/siuser/.ipython/cython/_cython_magic_9e64b76046e46a8c647811a3689ce26a.c:797)()

TypeError: Expected list, got int

2) For speed

Declare Python type: list


In [8]:
%%cython

def f(x, n):
    for i in range(n):
        x.append(i)

def g(list x, n):
    for i in range(n):
        x.append(i)

In [9]:
%timeit f([], 1000000)
%timeit g([], 1000000)


10 loops, best of 3: 36.8 ms per loop
10 loops, best of 3: 36.8 ms per loop

Declare Python type: set


In [10]:
%%cython

def h(x, n):
    for i in range(n):
        x.add(i)
    return x

def k(set x, n):
    for i in range(n):
        x.add(i)
    return x

In [11]:
%timeit h(set(), 1000000)
%timeit k(set(), 1000000)


10 loops, best of 3: 109 ms per loop
10 loops, best of 3: 70.5 ms per loop

In [ ]: