Zig is a different programming language, so we will not have enough time to go into the details of it, but you will know enough to get started and create a simple extension.
Please follow the getting started guide from the Zig language website in order to have the compiler.
You will find the instructions for macOS, Linux, and Windows, with many variations.
Add the following code into a file called hello.zig:
const std = @import("std");
pub fn main() !void {
std.debug.print("Hello, World!\n", .{});
}and to execute the code you can run:
zig run hello.zigyou can also build the code, to later run the binary manually:
$ zig build-exe hello.zig
$ ./hello
Hello, World!The project that enables Zig to be an option to write Python extensions is called Ziggy PyDust.
The binding generator uses poetry to handle projects and requires
some configuration.
First, create a pyproject.toml file with the following content:
[tool.poetry]
name = "hello_zig"
version = "1.0"
packages = [
{ include = "hello_zig*" }
]
include = [ { path = "src/", format = "sdist" } ]
[tool.poetry.build]
script = "build.py"
[build-system]
requires = ["poetry-core", "ziggy-pydust==0.25.1"]
build-backend = "poetry.core.masonry.api"
[[tool.pydust.ext_module]]
name = "hello_zig"
root = "src/hello.zig"Note
The packages entry matters here: hello_zig isn't a regular Python
package (there's no hello_zig/ directory or hello_zig.py file), it's a
compiled extension that Zig/pydust builds as hello_zig.abi3.so (or
hello_zig*.pyd on Windows). Without packages telling Poetry to grab that
file by name, poetry install will fail with No file/folder found for package hello-zig, since it can't auto-detect a package to install.
also, you need a simple build.py file alongside:
from pydust.build import build
build()and for the source code for our extension,
create a src directory and inside a file hello.zig with the content:
const py = @import("pydust");
const root = @This();
pub fn hello() !py.PyString(root) {
return try py.PyString(root).create("Hello, World!");
}
comptime {
py.rootmodule(root);
}With all the files in place, you can run poetry install to later execute
the code:
>>> from hello_zig import hello
>>> hello()
'Hello, World!'