GitXplorerGitXplorer
j

pythonlib

public
100 stars
12 forks
12 issues

Commits

List of commits on branch master.
Unverified
810c4154b1983e8ebb3fa191882fc98747f7a1a9

v0.17~preview.129.15+205

ppublic-release committed 10 months ago
Unverified
1c10dfa41d0cd3ccec2c27b980a0c146690da4fe

v0.17~preview.129.07+242

ppublic-release committed a year ago
Unverified
9ed8741cf0e49a164ffaba405ead1cadb1469283

v0.17~preview.129.00+111

ppublic-release committed a year ago
Unverified
2ddddbb38cc5751de736d24566bf315c42342900

v0.17~preview.128.47+23

ppublic-release committed a year ago
Unverified
2472c8df1ff85e8c667e5887534208f0252c80df

v0.17~preview.128.45+251

ppublic-release committed a year ago
Unverified
155f1de0c509534f397002ac303e4da91b284567

v0.17~preview.128.43+172

ppublic-release committed a year ago

README

The README file for this repository.

pythonlib makes it easier to write wrappers around ocaml functions so that they can be called from python.

Example

This example is taken from the examples directory. The ocaml code defines a function that takes as argument an integer n, performs some computations based on n and return a float value. This function is attached to a newly defined python module named ocaml_module.

open Base

let approx_pi =
  let%map_open.Python_lib n = positional "n" int ~docstring:""
  in
  let sum =
    List.init n ~f:(fun i -> let i = Float.of_int (1 + i) in 1.0 /. (i *. i))
    |> List.reduce_exn ~f:(+.)
  in
  Float.sqrt (sum *. 6.) |> python_of_float

let () =
  if not (Py.is_initialized ())
  then Py.initialize ();
  let mod_ = Py_module.create "example_module" in
  Py_module.set mod_ "approx_pi" approx_pi

This code is compiled to a static library ocaml.so, together with a small C library defining the PyInit_ocaml function that starts the ocaml runtime and exposes the example module. The python code then imports this library and can use the ocaml functions.

# This requires the ocaml.bc.so file to be copied as ocaml.so in the python path
from ocaml import example_module, toploop

# Import the module defined in the ocaml code and run the function.
import ocaml_module
print(ocaml_module.approx_pi(1000))

pythonlib also handles keyword arguments as well as basic types such as int, float, string, list, etc. Further examples can be found in the examples directory.