Let’s talk about something that might make you yawn faster than a PowerPoint presentation on tax reform C types in Python!
In Python, C types are just fancy names for data structures that we use all the time without even realizing it. For example, when you write `x = 5`, you’re actually assigning an integer (a type of data) to a variable named x. However, in C, things can get complicated.
C types come in two flavors: primitive and compound. Primitive types include integers, floats, doubles, characters, and booleans. Compound types involve arrays, structures, unions, and function pointers (which we won’t be covering today). Let’s focus on the primitive types for now.
Integers in C come in various flavors: signed and unsigned, as well as different sizes. A signed integer can have a value between -2147483648 (the smallest possible number) and 2147483647 (the largest). An unsigned integer has no negative values but can be much larger than its signed counterpart, with the maximum value being 4294967295.
Floats in C are also available in different sizes: single precision and double precision. A single-precision float (also known as a “float”) has about seven significant digits of accuracy, while a double-precision float (or “double”) can have up to 16 significant digits. Doubles are great for scientific calculations or when you need more precise results than what floats offer. However, they take up twice as much memory and can be slower to compute with. So choose wisely!
Now that we’ve covered the basics of C types, how to use them in Python. To do this, we’ll create a simple module called “c_types” (because why not?) that wraps some basic C functions for us to play with. First, open up your favorite text editor and create a new file named setup.py. This is where you’ll define the structure of your Python package:
# Import necessary modules
from distutils.core import setup # Importing the setup function from the distutils.core module
from Cython.Build import cythonize # Importing the cythonize function from the Cython.Build module
import numpy as np # Importing the numpy module and aliasing it as np for easier use
# Set up the package
setup( # Calling the setup function with the following arguments:
name='c_types', # Name of the package
ext_modules=cythonize("c_types.pyx") # List of extension modules to be compiled
)
This code tells the Python interpreter to use Cython (a tool that compiles Python code into C) and creates a new module called “c_types”. The .pyx file is where we’ll write our actual C code, so let’s create that next:
# Import the necessary libraries
import numpy as np # Importing numpy library and assigning it an alias "np"
cimport numpy as np # Importing numpy library for use in Cython
from libc.stdio cimport printf # Importing the printf function from the standard C library
cimport numpy.dtype cimport int32_t # Importing the int32_t data type from the numpy library
# Define a custom data type
ctypedef np.int32_t myint_t # Creating a custom data type called "myint_t" using the int32_t data type from numpy
# Define a function to add two numbers
def add(myint_t a, myint_t b): # Defining a function called "add" that takes in two parameters of type "myint_t"
ctypedefs [T_np.int32 for T in [a,b]] # Creating a list of ctypedefs for the two parameters
result = (a + b) # Adding the two parameters and assigning the result to a variable called "result"
printf("The sum of %d and %d is: %d\n", *ctypedefs) # Printing the sum of the two parameters using the printf function
return result # Returning the result of the addition
This code defines a new C function called “add” that takes two integers as input, adds them together, and prints the result to the console. The ctypedefs line creates a tuple of types for our inputs (which we’ll use later), while the printf statement formats our output string using the values in this tuple.
Now let’s test out our new module! Open up your Python interpreter and type:
# Import the c_types module
import c_types
# Define a function called "add" that takes in two parameters, "a" and "b"
def add(a, b):
# Create a tuple of types for our inputs, using the c_types module
ctypedefs = (c_types.c_int, c_types.c_int)
# Format our output string using the values in the tuple
printf("The sum of %d and %d is %d", (a, b, a + b))
# Call the add function with the values 5 and 10 as inputs
add(5, 10)
This should print “The sum of 5 and 10 is: 15” to the console. If you see an error message instead, make sure your setup.py file is in the same directory as your .pyx file (and that both are named correctly).
That’s it! You now have a basic understanding of C types in Python and how to use them with Cython. Of course, this was just a simple example there’s much more you can do with C types if you’re feeling adventurous. But for most purposes, this should be enough to get you started.
Later!