The Python bridge (37a, 37b)
A Python script is a capability: something you get from a directory you were granted, and pass to the code that may use it.
fn main(sys):
match dir(sys, "."):
Err(e) => print(e)
Ok(d) =>
match python(d, "helper.py"): # needs --allow-python (and read access to ".")
Err(e) => print(e)
Ok(py) =>
match py_call(py, "mean", "[[1, 2, 3, 4]]"):
Ok(v) => print(v) # "2.5": the result as JSON text
Err(e) => print(e) # "ValueError: ..." from the script
python(d: Dir, file: Str) -> Result[Py, Str]startspython3on a file insided(the same path confinement asread_file). It needs the--allow-pythongrant: Python is outside Trine's checks, so a program can't start one unless the person running it agreed.py_call(py: Py, function: Str, args_json: Str) -> Result[Str, Str]calls a top-level function of the script with the JSON array as its arguments, and returns its result as JSON text. Exceptions come back asErr("Type: message"). Names starting with_can't be called.Pyis a capability type:trine capsreports any function that can reach one ("a running Python script"), and it can't implement traits. Calls count as effects (no tier-up replay).- Protocol: the script runs under a small driver (
sysio::PY_DRIVER, shared by all engines) that reads two lines per call (the name as a JSON string, then the arguments) and answers one (O <json>orE <message>). Line framing means the argument text can't inject a second request or change the function name. The script's ownprintgoes to stderr. - The process ends when the last reference to the
Pyvalue is dropped.
Any module, objects by handle (37b)
fn report(py: Py) -> Result[Unit, Str]:
let pd = py_import(py, "pandas")?
let df = py_invoke(py_get(pd, "DataFrame")?, [JObj({"units": JArr([JNum(12.0), JNum(7.0)])})])?
let total = py_json(py_method(py_index(df, JStr("units"))?, "sum", [])?)?
print(json_int(total) ?? 0) # 19
Ok(())
fn main(sys):
match py_start(sys): # needs --allow-python
Ok(py) => print(report(py))
Err(e) => print(e)
examples/python/pandas_report.tr builds a DataFrame from Trine records, groups it and brings the numbers back; a test runs it on the interpreter, the VM and native code.
py_start(sys) -> Result[Py, Str]starts a Python process for any importable module (the same--allow-pythongrant). The library (python.tr, written in Trine overpy_calland the JSON library) works on it: -py_import(py, name),py_get(o, attr),py_index(o, key),py_invoke(f, args),py_invoke_kw(f, args, kwargs),py_method(o, name, args),py_value(py, json): each gives aPyObj, a handle to an object that stays in Python; - arguments areJsonvalues;py_ref(o)passes an object itself; -py_json(o) -> Result[Json, Str]brings a value back: numbers, text, lists, dicts, and pandas/numpy values through theirto_dict/tolist(NaN and infinities become null);py_text(o)isstr(o); -py_free(o)lets Python free an object; otherwise objects live as long as the process.- Every Python exception comes back as an
Err("Type: message"); nothing in Python can stop or corrupt the Trine program. - Why a process and not libpython linked in: the same bridge works on every engine (the interpreter, the VM, native code, every platform) with no build-time dependency on a Python version, and a crash or a leak in a C extension can't corrupt Trine's memory or break its ownership rules. The cost is a round trip per call (tens of microseconds): call Python for whole-array work, not per element.