1. Ariovistus
  2. pyd


Clone wiki

pyd / FuncWrap

Function wrapping

Exposing D functions to Python is easy!

See also


The heart of Pyd's function wrapping features is the def template function.

Notes on def

  • All calls to def must occur before calling module_init.
  • Any function whose return type and arguments are convertible can be wrapped by def.
  • def can only wrap functions with in arguments (not out or ref or lazy).
  • def can handle functions with default and typesafe variadic (e.g. void foo(T[]...)) arguments.
  • def supports skipping default arguments (on the python side) and will automatically fill in any omitted default arguments.
  • def-wrapped functions can take keyword arguments in python.

def-wrapped functions can be called in python in the following ways:

D functionPython call
void foo(int i);foo(1), foo(i=1)
void foo(int i, double d = 3.14);foo(1,2.0), foo(1), foo(i=1), etc
void foo(int i = 2, double d = 3.14foo(d=3.0)
void foo(int[] i...);foo(1), foo(1,2,3), foo([1,2,3]), foo(i=1), foo(i=[1,2,3])


import pyd.pyd;
import std.stdio;

void foo(int i) {
    writefln("You entered ", i);

void bar(int i) {
    writefln("bar: i = ", i);

void bar(char[] s) {
    writefln("bar: s = ", s);

void baz(int i=10, char[] s="moo") {
    writefln("i = %s\ns = %s", i, s);

extern (C) void PydMain() {
    // Plain old function
    // Wraps the lexically first function under the given name
    def!(bar, PyName!"bar1");
    // Wraps the function of the specified type
    def!(bar, PyName!"bar2", void function(char[]));
    // Wraps the function with default arguments


And when used in Python:

>>> import testmodule
>>> testmodule.foo(10)
You entered 10
>>> testmodule.bar1(20)
bar: i = 20
>>> testmodule.bar2("monkey")
bar: s = monkey
>>> testmodule.baz()
i = 10
s = moo
>>> testmodule.baz(3)
i = 3
s = moo
>>> testmodule.baz(4, "apple")
i = 4
s = apple