Skip to content

Mypyc C Code Generator

Jukka Lehtosalo edited this page Oct 24, 2022 · 2 revisions

Mypyc compiles a function into two functions, a native function and a wrapper function:

  • The native function takes a fixed number of C arguments with the correct C types. It assumes that all argument have correct types.

  • The wrapper function conforms to the Python C API calling convention and takes an arbitrary set of arguments as Python objects. It processes the arguments, checks their types, unboxes values with special representations and calls the native function. The return value from the native function is translated back to a Python object ("boxing").

Calls to other compiled functions don't go through the Python module namespace but directly call the target native C function. This makes calls very fast compared to CPython. This is called early binding.

Currently early binding is only possible between modules that are compiled together. If you, for example, install a module compiled with mypyc using pip, and use it in your code, calls to the installed module will use slow Python-level calls.

The generated code does runtime type checking so that it can assume that values always have the declared types. Whenever accessing CPython values which might have unexpected types we need to insert a runtime type check operation. For example, when getting a list item we need to insert a runtime type check (an unbox or a cast operation), since Python lists can contain arbitrary objects.

The generated code uses various helpers defined in mypyc/lib-rt/CPy.h. The implementations are in various .c files under mypyc/lib-rt.