Clone wiki

pyd / Embedded

Embedding Python in D

A minimal D program with embedded python might look like this:

import pyd.pyd; 

shared static this() {
    py_init();
}
void main() {
}

Of interest in pyd.pyd are PydObject, py, and d_type, which are documented elsewhere, and py_init, which calls Py_Initialize and handles details relating to extending embedded python.

Examples

import pyd.pyd, pyd.embedded;
import std.stdio;

shared static this() {
  on_py_init({
     add_module("module1");
  });
  py_init();
}

alias py_def!(q"<
def fun1(a,b,c):
    return "funzy(%x, %f, %r)" % (a,b,c)
>", "module1",
string function(int, float, string)) Fun1;

void main() {
    string s = Fun1(int.min, 4.44, "hello world");
    writeln(s);
}

This example introduces us to three new functions: on_py_init, add_module, and py_def.

add_module is used to create a new python module in the embedded interpreter. Since the underlying mechanics vary sufficiently between python 2 and python 3, add_module must only be called from within on_py_init

py_def can be used to define a python function and then call it in D as if it were a D function

Updated