Skip to content

Python Functions

Python functions can be declared as usual zig functions at top level of the module

1
2
3
4
5
6
7
8
9
const py = @import("pydust");

pub fn double(args: struct { x: i64 }) i64 {
    return args.x * 2;
}

comptime {
    py.rootmodule(@This());
}

Functions come with __text_signature__ support out of the box. Function double will have signature (x, /).

Functions also accept keyword arguments as regular python function. Argument is deemed to be a kwarg argument if it has a default value associated with it for a function:

1
2
3
pub fn with_kwargs(args: struct { x: f64, y: f64 = 42.0 }) f64 {
    return if (args.x < args.y) args.x * 2 else args.y;
}

The generated signature will be (x, /, *, y=42.0)

Python's variadic arguments *args and **kwargs are represented by including py.Args and py.Kwargs attributes in your args struct.

1
2
3
4
5
6
pub fn variadic(args: struct { hello: py.PyString, args: py.Args, kwargs: py.Kwargs }) !py.PyString {
    return py.PyString.createFmt(
        "Hello {s} with {} varargs and {} kwargs",
        .{ try args.hello.asSlice(), args.args.len, args.kwargs.count() },
    );
}