Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/pyxtend/struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 9 additions & 1 deletion tests/unit/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down