From d585676a3510a8f5740afb15247c44e3decabb50 Mon Sep 17 00:00:00 2001 From: Julius Simonelli Date: Sun, 23 Nov 2025 11:04:26 -0800 Subject: [PATCH] Add ndarray example previews when requested --- src/pyxtend/struct.py | 15 +++++++++++++-- tests/unit/test_struct.py | 10 +++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/pyxtend/struct.py b/src/pyxtend/struct.py index 5e4826d..021655d 100644 --- a/src/pyxtend/struct.py +++ b/src/pyxtend/struct.py @@ -26,10 +26,21 @@ def struct(obj: Any, level: int = 0, limit: int = 3, examples: bool = False) -> # This works for both TensorFlow and PyTorch return {obj_type_name: [f"{obj.dtype}, shape={tuple(getattr(obj, 'shape', ()))}"]} elif obj_type_name == "ndarray": - inner_structure = "empty" if obj.size == 0 else struct(obj.item(0), level + 1) shape = tuple(obj.shape) dtype = obj.dtype.name - return {f"{type(obj).__name__}": [f"{dtype}, shape={shape}"]} + summary = f"{dtype}, shape={shape}" + + if not examples: + return {f"{type(obj).__name__}": [summary]} + + preview_limit = 3 + flat = obj.flatten() + preview = flat[:preview_limit].tolist() + + if flat.size > preview_limit: + preview.append(f"...{flat.size} total") + + return {f"{type(obj).__name__}": [summary, *preview]} elif obj_type_name == "Polygon": coords = list(getattr(obj, "exterior", {}).coords) if hasattr(obj, "exterior") else [] shape = (len(coords), len(coords[0]) if coords else 0) diff --git a/tests/unit/test_struct.py b/tests/unit/test_struct.py index c203ede..a650b2a 100644 --- a/tests/unit/test_struct.py +++ b/tests/unit/test_struct.py @@ -112,7 +112,15 @@ def test_numpy_array_examples(): # maybe include three? result = struct(np_arr, examples=True) # Reponse will depend on default interger type of the platform expected_dtype = "int32" if np.dtype("int").itemsize == 4 else "int64" - assert result == {"ndarray": [f"{expected_dtype}, shape=(7,)"]} + assert result == {"ndarray": [f"{expected_dtype}, shape=(7,)", 1, 2, 3, "...7 total"]} + + +def test_numpy_array_examples_vs_structure(): + np_arr = np.array([1, 2, 3]) + without_examples = struct(np_arr, examples=False) + with_examples = struct(np_arr, examples=True) + + assert without_examples != with_examples def test_dict():