mypyc command compiles Python modules to C extensions using mypy’s type analysis. This can significantly improve the performance of your Python code while maintaining compatibility with the standard Python interpreter.
Overview
Mypyc compiles type-annotated Python code to C, creating extension modules that can be imported and used like normal Python modules. It uses mypy’s static analysis to generate efficient C code.Basic usage
How it works
- Type analysis: Uses mypy to analyze your code and its types
- C code generation: Generates C code based on the type information
- Compilation: Compiles the C code to a native extension module
- Installation: Places the compiled module where Python can import it
The compiled modules are fully compatible with regular Python code. You can mix compiled and interpreted code freely.
Environment variables
Mypyc behavior can be controlled through environment variables:Optimization level for the compiler.Values:
0 (no optimization) to 3 (maximum optimization)Default: 3Debug information level.Values:
0 (no debug info) to 3 (maximum debug info)Default: 1Enable strict typing for dunder methods.Values:
0 (disabled), 1 (enabled)Default: 0Enable sampled operation logging.Values:
0 (disabled), 1 (enabled)When enabled, writes a log of executed operations to mypyc_trace.txt.Default: 0Examples
Example: Performance boost
Here’s a simple example showing the potential speedup:fibonacci.py
Requirements for best results
To get optimal performance from mypyc:- Add type annotations: More type information = better optimization
- Use primitive types:
int,float,boolcompile to efficient C types - Avoid
Any: Unknown types prevent optimization - Type class attributes: Allows direct field access instead of dictionary lookups
- Use final classes: Enables devirtualization of method calls
Limitations
Some Python features are not supported or have limited support:- Dynamic code execution:
eval(),exec()not supported - Some magic methods: Limited support for some special methods
- Reflection: Some introspection features may not work
- Monkey patching: Compiled code can’t be easily modified at runtime
Integration with setuptools
For building distributable packages with mypyc:setup.py
Debugging compiled code
When debugging mypyc-compiled modules:Performance tips
Building for distribution
When distributing mypyc-compiled packages:- Include source: Always ship both .py and compiled modules
- Platform-specific: Build wheels for each target platform
- Fallback: Ensure code works interpreted if compilation fails
- Test compiled: Test both compiled and interpreted versions
pyproject.toml