Python -> Javascript ipywidget serializer This function must repalce all objects that the ipywidget library can't serialize natively (e.g. numpy arrays) with serializable representations Parameters ---------- v Object to be serialized widget_manager
(v, widget_manager)
| 5 | |
| 6 | |
| 7 | def _py_to_js(v, widget_manager): |
| 8 | """ |
| 9 | Python -> Javascript ipywidget serializer |
| 10 | |
| 11 | This function must repalce all objects that the ipywidget library |
| 12 | can't serialize natively (e.g. numpy arrays) with serializable |
| 13 | representations |
| 14 | |
| 15 | Parameters |
| 16 | ---------- |
| 17 | v |
| 18 | Object to be serialized |
| 19 | widget_manager |
| 20 | ipywidget widget_manager (unused) |
| 21 | |
| 22 | Returns |
| 23 | ------- |
| 24 | any |
| 25 | Value that the ipywidget library can serialize natively |
| 26 | """ |
| 27 | |
| 28 | # Handle dict recursively |
| 29 | # ----------------------- |
| 30 | if isinstance(v, dict): |
| 31 | return {k: _py_to_js(v, widget_manager) for k, v in v.items()} |
| 32 | |
| 33 | # Handle list/tuple recursively |
| 34 | # ----------------------------- |
| 35 | elif isinstance(v, (list, tuple)): |
| 36 | return [_py_to_js(v, widget_manager) for v in v] |
| 37 | |
| 38 | # Handle numpy array |
| 39 | # ------------------ |
| 40 | elif np is not None and isinstance(v, np.ndarray): |
| 41 | # Convert 1D numpy arrays with numeric types to memoryviews with |
| 42 | # datatype and shape metadata. |
| 43 | if ( |
| 44 | v.ndim == 1 |
| 45 | and v.dtype.kind in ["u", "i", "f"] |
| 46 | and v.dtype != "int64" |
| 47 | and v.dtype != "uint64" |
| 48 | ): |
| 49 | # We have a numpy array the we can directly map to a JavaScript |
| 50 | # Typed array |
| 51 | return {"buffer": memoryview(v), "dtype": str(v.dtype), "shape": v.shape} |
| 52 | else: |
| 53 | # Convert all other numpy arrays to lists |
| 54 | return v.tolist() |
| 55 | |
| 56 | # Handle Undefined |
| 57 | # ---------------- |
| 58 | if v is Undefined: |
| 59 | return "_undefined_" |
| 60 | |
| 61 | # Handle simple value |
| 62 | # ------------------- |
| 63 | else: |
| 64 | return v |