pyfunction
Wrap a Nelson function handle as a Python callable.
📝Syntax
c = pyfunction(fun_handle)
📥Input Arguments
Parameter Description
fun_handle a function handle: anonymous (for example @(x) x .^ 2) or named (for example @sin).
📤Output Arguments
Parameter Description
c a Python callable object (py.builtin_function_or_method) that forwards its calls to the Nelson function handle.
📄Description

c = pyfunction(fun_handle) wraps a Nelson function handle into a Python callable object. When Python code calls c, the wrapped Nelson function handle runs synchronously in the same Nelson session and its result is returned to Python.

This is the reverse direction of pyrun: instead of Nelson calling Python, Python calls Nelson. Pass the callable to Python with the name-value arguments of pyrun or pyrunfile, then call it from the Python code. It can be given to any Python API that expects a callable, for example a scikit-learn custom scorer, kernel, or transformer.

When Python calls the wrapped callable, the positional arguments are converted to Nelson values (Python scalars and NumPy arrays follow the same rules as the other python_engine conversions), the Nelson function handle is evaluated, and its single output is converted back to a Python object. Handles that return no value produce Python None.

A Nelson error raised inside the callback becomes a Python exception whose message contains the Nelson message, and it is then surfaced cleanly in Nelson.

Limitations. The callback is in-process and single-threaded: the Nelson function handle always runs on the Nelson interpreter thread. It is designed for single-threaded use only. With scikit-learn and joblib, use n_jobs=1; backends that spawn worker processes or threads (n_jobs greater than 1) cannot call back into the parent Nelson session, and a call arriving from an unexpected thread fails with a clear error instead of corrupting the session. Calling pyrun or pyrunfile again from within a callback is not supported and raises an error rather than deadlocking. Only a single output is supported.

💡Examples
Call an anonymous handle from Python.
sq = @(x) x .^ 2;
f = pyfunction(sq);
y = pyrun("r = g(4.0)", "r", "g", f)
Receive a NumPy array in the callback.
add1 = @(v) double(v) + 1;
f = pyfunction(add1);
o = pyrun("import numpy as np; o = g(np.array([1.0, 2.0, 3.0]))", "o", "g", f)
Use a named function handle.
f = pyfunction(@sin);
z = pyrun("r = g(0.0)", "r", "g", f)
🔗See Also
pyrunpyrunfileCall Nelson from PythonPython types supported
🕔Version History
Version Description
2.0.0 initial version
Edit this page on GitHub