Skip to content

Commit 11f7499

Browse files
committed
improve error messages, compactify tests, add special case for disambiguating ints from bools
1 parent bbd8ba7 commit 11f7499

2 files changed

Lines changed: 566 additions & 84 deletions

File tree

src/zarr/core/type_check.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,10 @@ def check_type(obj: Any, expected_type: Any, path: str = "value") -> TypeCheckRe
235235
):
236236
return check_mapping(obj, expected_type, path)
237237

238-
if expected_type in (int, float, str, bool):
238+
if expected_type is int:
239+
return check_int(obj, path)
240+
241+
if expected_type in (float, str, bool):
239242
return check_primitive(obj, expected_type, path)
240243

241244
# Fallback
@@ -257,7 +260,9 @@ def ensure_type(obj: object, expected_type: type[T], path: str = "value") -> T:
257260
"""
258261
if check_type(obj, expected_type, path).success:
259262
return cast(T, obj)
260-
raise TypeError(f"Expected {expected_type} but got {obj!r} with type {type(obj)}")
263+
raise TypeError(
264+
f"Expected an instance of {expected_type} but got {obj!r} with type {type(obj)}"
265+
)
261266

262267

263268
def guard_type(obj: object, expected_type: type[T], path: str = "value") -> TypeGuard[T]:
@@ -423,14 +428,22 @@ def check_primitive(obj: object, expected_type: type, path: str) -> TypeCheckRes
423428
"""
424429
Check if an object is a primitive type, i.e. a type where isinstance(obj, type) will work.
425430
"""
426-
if "value['shape']" in path and expected_type is not int:
427-
breakpoint()
428431
if isinstance(obj, expected_type):
429432
return TypeCheckResult(True, [])
430433
msg = f"{path} expected an instance of {expected_type} but got {obj!r} with type {type(obj)}"
431434
return TypeCheckResult(False, [msg])
432435

433436

437+
def check_int(obj: object, path: str) -> TypeCheckResult:
438+
"""
439+
Check if an object is an int.
440+
"""
441+
if isinstance(obj, int) and not isinstance(obj, bool): # bool is a subclass of int
442+
return TypeCheckResult(True, [])
443+
msg = f"{path} expected int but got {obj!r} with type {type(obj)}"
444+
return TypeCheckResult(False, [msg])
445+
446+
434447
def _get_typeddict_metadata(
435448
td_type: Any,
436449
) -> tuple[

0 commit comments

Comments
 (0)