Skip to content

Commit

Permalink
Verbose error handling for non-valid duckarrays (#9314)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Illviljan authored Aug 8, 2024
1 parent bd0fd97 commit b22c429
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion xarray/tests/test_namedarray.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import copy
import sys
from abc import abstractmethod
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Generic, cast, overload
Expand Down Expand Up @@ -86,7 +87,29 @@ def check_duck_array_typevar(a: duckarray[Any, _DType]) -> duckarray[Any, _DType
if isinstance(b, _arrayfunction_or_api):
return b
else:
raise TypeError(f"a ({type(a)}) is not a valid _arrayfunction or _arrayapi")
missing_attrs = ""
actual_attrs = set(dir(b))
for t in _arrayfunction_or_api:
if sys.version_info >= (3, 13):
# https://github.com/python/cpython/issues/104873
from typing import get_protocol_members

expected_attrs = get_protocol_members(t)
elif sys.version_info >= (3, 12):
expected_attrs = t.__protocol_attrs__
else:
from typing import _get_protocol_attrs # type: ignore[attr-defined]

expected_attrs = _get_protocol_attrs(t)

missing_attrs_ = expected_attrs - actual_attrs
if missing_attrs_:
missing_attrs += f"{t.__name__} - {missing_attrs_}\n"
raise TypeError(
f"a ({type(a)}) is not a valid _arrayfunction or _arrayapi. "
"Missing following attrs:\n"
f"{missing_attrs}"
)


class NamedArraySubclassobjects:
Expand Down

0 comments on commit b22c429

Please sign in to comment.