Skip to main content

Compile and import Zig functions at runtime without building a package

Project description

import-zig

pip install import-zig

This module provides a way to import Zig code directly into Python using a single function call to import_zig. Here is an example:

from import_zig import import_zig

mod = import_zig(source_code = """
    pub fn Q_rsqrt(number: f32) f32 {
        const threehalfs: f32 = 1.5;
        const x2 = number * 0.5;
        var y = number;
        var i: i32 = @bitCast(y);
        i = 0x5f3759df - (i >> 1);
        y = @bitCast(i);
        y = y * (threehalfs - (x2 * y * y));

        return y;
    }
""")

print(f"1 / sqrt(1.234) = {mod.Q_rsqrt(1.234)}")

The main goal of this module is to make it easy to prototype Zig extensions for Python without having to engage with the Python build system. When building larger Zig extensions it is likely preferable to write your own build process with setuptools or to use a ziggy-pydust template, which provides a comptime abstraction over many aspects of the Python C API. Zig and Zig extensions are still very new though, so things will likely change. Technically you could also use this module as part of a packaging step by calling the compile_to function to build the binary and moving it into the packages build folder.

One approach that I expect to stay the same is the comptime wrapping for conversion between Zig and Python types as well as exception handling. This is conveniently packed into the file py_utils.zig and could be copy pasted into a new setuptools based project and maybe adjusted.

See the docs of the import_zig function for more details or check out the examples directory.

File structure

The file structure that will be generated to compile the Zig code looks as follows.

project_folder
├── build.zig
├── generated.zig
├── inner
│   └── import_fns.zig
├── py_utils.zig
└── zig_ext.zig

The inner directory is where your code lives. When you pass a source code string or file path, it will be written / linked as the import_fns.zig file. When you pass a directory path, the directory will be linked as the inner directory above, enabling references to other files in the directory path.

The above file structure can be generated with:

import_zig.prepare("/path/to/project_folder", "module_name")

This enables ZLS support for the Python C API when importing py_utils from import_fns.zig.

Type mapping

The conversion is defined in py_utils.zig and applied based on the parameter / return types of the exported function. Errors are also forwarded. The solution to passing variable length data back to Python is a bit of a hack: When an exported function specifies std.mem.Allocator as a parameter type, then an arena allocator - which gets deallocated after the function call - will be passed into the function. The allocator can then be used to allocate and return new slices for example.

For nested types, the conversion is applied recursively.

Conversion from Python Zig datatype Conversion to Python
int integer (any size / sign) int
float float (any size) float
- void None
evaluated like bool() bool bool
sequence array list
sequence non u8 const slice list
str u8 const slice str
dict or sequence struct tuple if struct is a tuple or named tuple
comparison with None optional null -> None

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

import_zig-0.14.0.tar.gz (12.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

import_zig-0.14.0-py3-none-any.whl (11.8 kB view details)

Uploaded Python 3

File details

Details for the file import_zig-0.14.0.tar.gz.

File metadata

  • Download URL: import_zig-0.14.0.tar.gz
  • Upload date:
  • Size: 12.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for import_zig-0.14.0.tar.gz
Algorithm Hash digest
SHA256 d3a6ab533bef682b67b9b7486eb57b7a728a7801fbc0fa163c4f1d03fa2fdb4a
MD5 349a29aac0d95d5dac809ce616b7c048
BLAKE2b-256 2bfed3de386d4fb7530992cd12778e02c9789a748c4164de4785f9ee6d36b483

See more details on using hashes here.

File details

Details for the file import_zig-0.14.0-py3-none-any.whl.

File metadata

  • Download URL: import_zig-0.14.0-py3-none-any.whl
  • Upload date:
  • Size: 11.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for import_zig-0.14.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6d381ce3cecfb1409458222cf7400aaa43f2216b2d23f8e73f701392502af75f
MD5 c676613aa0bd3be8ddaa73ab58f2ab15
BLAKE2b-256 324c6ef87cd720b74fc8832ca95b312b26ae7fb84d7bd52f66ef2e1b317a0df5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page