[ANN] ocaml-in-python.0.1.0: Effortless Python bindings for OCaml modules

I am happy to announce the first release of ocaml-in-python: this is a Python package that exposes all OCaml modules as Python libraries, generating bindings on the fly. This can be seen as a dual of pyml_bindgen: pyml_bindgen binds Python libraries in OCaml, while ocaml-in-python binds OCaml modules in Python.

It is available from GitHub or via opam: opam install ocaml-in-python

Requirements: OCaml >= 4.13, Python >= 3.7.

Once installed via opam, the package should be registered in the Python environment:

  • either by registering the package with pip using the following command (requires Python >=3.8):
pip install --editable "`opam var ocaml-in-python:lib`"
  • or by adding the following definition to the environment:
export PYTHONPATH="`opam var share`/python/:$PYTHONPATH"

Then, we can import ocaml in Python and use OCaml modules:

Python 3.10.0 (default, Nov 10 2021, 19:16:14) [GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ocaml
>>> print(ocaml.List.map((lambda x : x + 1), [1, 2, 3]))
[2;3;4]

We can for instance compile an OCaml module on the fly from Python.

>>> m = ocaml.compile('let hello x = Printf.printf "Hello, %s!\n%!" x')
>>> m.hello('world')
Hello, world!

And we can require and use packages via findlib.

>>> ocaml.require("parmap")
>>> from ocaml import Parmap
>>> print(Parmap.parmap(
...   (lambda x : x + 1), Parmap.A([1, 2, 3]), ncores=2))
[2;3;4]

Details about the conversions are given in README.md.

Happy hacking!

16 Likes

Very nice if I have something difficult to program but the users only care that “it must be usable from Python”.

1 Like