Skip to content

Commit b22c429

Browse files
authored
Verbose error handling for non-valid duckarrays (#9314)
* Add helpful error for non-duckarrays * Add proof of concept * Update test_namedarray.py * Update test_namedarray.py * Update test_namedarray.py * remove test * Update test_namedarray.py
1 parent bd0fd97 commit b22c429

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

xarray/tests/test_namedarray.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import copy
4+
import sys
45
from abc import abstractmethod
56
from collections.abc import Mapping
67
from typing import TYPE_CHECKING, Any, Generic, cast, overload
@@ -86,7 +87,29 @@ def check_duck_array_typevar(a: duckarray[Any, _DType]) -> duckarray[Any, _DType
8687
if isinstance(b, _arrayfunction_or_api):
8788
return b
8889
else:
89-
raise TypeError(f"a ({type(a)}) is not a valid _arrayfunction or _arrayapi")
90+
missing_attrs = ""
91+
actual_attrs = set(dir(b))
92+
for t in _arrayfunction_or_api:
93+
if sys.version_info >= (3, 13):
94+
# https://github.com/python/cpython/issues/104873
95+
from typing import get_protocol_members
96+
97+
expected_attrs = get_protocol_members(t)
98+
elif sys.version_info >= (3, 12):
99+
expected_attrs = t.__protocol_attrs__
100+
else:
101+
from typing import _get_protocol_attrs # type: ignore[attr-defined]
102+
103+
expected_attrs = _get_protocol_attrs(t)
104+
105+
missing_attrs_ = expected_attrs - actual_attrs
106+
if missing_attrs_:
107+
missing_attrs += f"{t.__name__} - {missing_attrs_}\n"
108+
raise TypeError(
109+
f"a ({type(a)}) is not a valid _arrayfunction or _arrayapi. "
110+
"Missing following attrs:\n"
111+
f"{missing_attrs}"
112+
)
90113

91114

92115
class NamedArraySubclassobjects:

0 commit comments

Comments
 (0)