In [1]:
%load_ext cython

In [2]:
def f():
    """ A useless function f() which adds some values together """
    continent_index = 3  # Africa = 0, S.America = 1, Australia = 2, etc.
    wonder_of_the_world = 6  # Giza = 0, Babylon = 1, Olympia = 2, etc. 
    age = 21  # years
    height = 1.83  # metres
    total_debt = 18000000000000  # 18 trillion
    depth = -60.123  # metres
    milky_way_mass = 6e42  # kg
    valid = False
    return (continent_index + age + height + total_debt + milky_way_mass)

In [3]:
f()


Out[3]:
6e+42

Adding Cython types


In [4]:
%%cython -a
cdef double f():
    cdef:
        unsigned char continent_index = 3
        unsigned char wonder_of_the_world = 6
        int age = 21  # years
        float height = 1.83
        float depth = -60.123  # metres
        long long total_debt = 18000000000000  # 18 trillion
        double milky_way_mass = 6e42  # kg
        bint valid = False
    return (continent_index + age + height + total_debt + milky_way_mass)


Out[4]:
Cython: _cython_magic_8d6bae31e38fec06f1236870c92d74d9.pyx

Generated by Cython 0.25.2

Yellow lines hint at Python interaction.
Click on a line that starts with a "+" to see the C code that Cython generated for it.

+01: cdef double f():
static double __pyx_f_46_cython_magic_8d6bae31e38fec06f1236870c92d74d9_f(void) {
  unsigned char __pyx_v_continent_index;
  CYTHON_UNUSED unsigned char __pyx_v_wonder_of_the_world;
  int __pyx_v_age;
  float __pyx_v_height;
  CYTHON_UNUSED float __pyx_v_depth;
  PY_LONG_LONG __pyx_v_total_debt;
  double __pyx_v_milky_way_mass;
  CYTHON_UNUSED int __pyx_v_valid;
  double __pyx_r;
  __Pyx_RefNannyDeclarations
  __Pyx_RefNannySetupContext("f", 0);
/* … */
  /* function exit code */
  __pyx_L0:;
  __Pyx_RefNannyFinishContext();
  return __pyx_r;
}
 02:     cdef:
+03:         unsigned char continent_index = 3
  __pyx_v_continent_index = 3;
+04:         unsigned char wonder_of_the_world = 6
  __pyx_v_wonder_of_the_world = 6;
+05:         int age = 21  # years
  __pyx_v_age = 21;
+06:         float height = 1.83
  __pyx_v_height = 1.83;
+07:         float depth = -60.123  # metres
  __pyx_v_depth = -60.123;
+08:         long long total_debt = 18000000000000  # 18 trillion
  __pyx_v_total_debt = 0x105EF39B2000;
+09:         double milky_way_mass = 6e42  # kg
  __pyx_v_milky_way_mass = 6e42;
+10:         bint valid = False
  __pyx_v_valid = 0;
+11:     return (continent_index + age + height + total_debt + milky_way_mass)
  __pyx_r = ((((__pyx_v_continent_index + __pyx_v_age) + __pyx_v_height) + __pyx_v_total_debt) + __pyx_v_milky_way_mass);
  goto __pyx_L0;

In [5]:
f()


Out[5]:
6e+42

In [ ]: