Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

PyCell Example

example.livemd

PyCell Example

Mix.install([
  {:py_cell, github: "NduatiK/py_cell"}
])

Section

require PyCell

code = """
def add(a, b):
  return a + b
"""

PyCell.open_port("add", code)
PyCell.run("add", [1, 2])

A more complex example

require PyCell

code = """
# You can define classes
class Subtracter:
  def __init__(self):
    self.zero = 0

  def sub(self, a, b):
    return a - b + self.zero

# You can define globals
subtracter = Subtracter()

# Only `sub` will be exposed
def sub(a, b):
  return subtracter.sub(a, b)
"""

PyCell.open_port("sub", code)
PyCell.run("sub", [1, 3])

Error Handling

require PyCell

code = """
def error(a, b):
  return a + b + c
"""

PyCell.open_port("error", code)

Running the following code will produce a Python error.

PyCell.run("error", [1, 2])

Is it fast?

No, not at all. In the simple benchmark below, subtracting 100K numbers through Python takes 300x longer than in Elixir. So this only makes sense when the operations would be much faster in Python.

A great place for this is when doing matrix multiplication. Numpy is sometimes faster than Nx and can handle numpy archives that contain strings.

:timer.tc(fn ->
  for _ <- 1..100_000 do
    PyCell.run("sub", [1, 2])
  end
end)
|> elem(0)
|> then(&amp;(&amp;1 / 1_000_000))
:timer.tc(fn ->
  for _ <- 1..100_000 do
    1 - 2
  end
end)
|> elem(0)
|> then(&amp;(&amp;1 / 1_000_000))