Skip to content

Commit

Permalink
ADD: objects can override is_dict_like()
Browse files Browse the repository at this point in the history
By setting obj._xarray_dict_like_, any object obj can now tell xarray to treat it like it is (or is not) a dict. This is useful if using custom objects for coordinates, when those objects store information in a dict-like format, but that information is not related to xarray and there's no reason for xarray to treat the objects as dicts.
  • Loading branch information
Sevans711 committed Jan 16, 2024
1 parent 33d51c8 commit 7a0f95d
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion xarray/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,14 @@ def remove_incompatible_items(

# It's probably OK to give this as a TypeGuard; though it's not perfectly robust.
def is_dict_like(value: Any) -> TypeGuard[Mapping]:
return hasattr(value, "keys") and hasattr(value, "__getitem__")
"""Return whether to treat value like it is a dictionary.
Usually, just tests whether value has 'keys' and '__getitem__' attributes.
However, if value._xarray_dict_like_ exists, return that instead.
"""
try:
return value._xarray_dict_like_
except AttributeError:
return hasattr(value, "keys") and hasattr(value, "__getitem__")


def is_full_slice(value: Any) -> bool:
Expand Down

0 comments on commit 7a0f95d

Please sign in to comment.