Bridging between Static and Dynamic typing in Cython(In web)
Created By: Talha9870 at Jan. 24, 2021
In a few of our previous tutorial, we are exploring static versus dynamic typing. Both of these options have their pros and cons. Static typing provides better performance, while dynamic typing provides convenience. But wait, why not use both of these types together, so we can combine the performance of static typing with the ease of dynamic typing. That’s the thing we are going to talk about in this video.
Cython allows assignments between statically and dynamically typed variables. This blending of static and dynamic is a powerful feature that we can use in several situations: it allows us to use dynamic Python objects for the majority of our codebase, and easily convert them into fast, statically typed analogues for the performance-critical sections.
cdef int a, b, c
So, let's see an example. Here you can see we have defined some variables named a, b, and c of type integers by using the cdef keyword. There are static variables. On the next line we defined a python tuple named tuple_of_int by using the static variables, this tuple is dynamically typed.
The simplicity of this example is part of Python's power and beauty: we can just create a tuple of C ints in the obvious way without further thought. We want conceptually simple things like this to be simple, and that is what Cython provides us.
This example works because there is an obvious correspondence between C ints and Python ints, so Python can transform things automatically for us.
This example would not work as-is if a, b, and c were, for example, C pointers. In that case, we would have to dereference them before putting them into the tuple or use another strategy.
So, here in this table you can see the Type correspondence between built-in Python types and C or C++ types for some types.
From python boolean to C bint. The bint Boolean integer type is an int at the C level and is converted to and from a Python bool. It has the standard C interpretation of truthiness: zero represents the False while nonzero represents True.
From Python float to float,double, long double. A Python float is stored as a C double. Converting a Python float to a C float may truncate to positive or negative infinity, according to IEEE conversion rules.
From Python complex to float complex and double complex. The Python complex type is stored as a C struct of two doubles.
Cython has float complex and double complex C-level types, which correspond to the Python complex type. The C types have the same interface as the Python complex type, but use efficient C-level operations. Another one is from Python dict to python's struct.
Great, so that’s how we can combine the static and dynamic typing from Python and Cython and utilize the pros from both options to make our life easier.