Kino.Pythonx (KinoPythonx v0.1.0)

View Source

Pythonx integration with Kino.

This packages defines rendering for a number of Python types and allows for defining custom ones via register_render/2.

Summary

Functions

Registers a render function for Pythonx objects of the given class.

Functions

register_render(class, render)

@spec register_render(String.t() | [String.t()], (Pythonx.Object.t() -> term())) ::
  :ok

Registers a render function for Pythonx objects of the given class.

The class name should be fully-qualified, that is, include the module name, for example "pandas.DataFrame". The render applies to objects that are instances of the given class, inclusing derived classes.

The render function receives a Pythonx.Object and should return any term, which is subsequently dispatched to Kino.Render protocol.

In case you want to release custom render implementations as a package, you should call the registrations on application startup, and for consistency name the package kino_pythonx_*.

Examples

Kino.Pythonx.register_render("matplotlib.artist.Artist", fn value ->
  {result, %{}} =
    Pythonx.eval(
      """
      import io
      buffer = io.BytesIO()
      value.figure.savefig(buffer, format="png", bbox_inches="tight")
      data = buffer.getvalue()
      buffer.close()
      data
      """,
      %{"value" => value}
    )

  data = Pythonx.decode(result)
  Kino.Image.new(data, "image/png")
end)