-
I am trying to improve typing in xarray and stumbled upon the following problem: numpys Some parts of xarrays code require a Mapping from variables to dtypes and will create this mapping if a single dtype is provided (i.e. if not isinstance(dtype, Mapping):
dtype_ = {k: dtype for k in other.data_vars.keys()}
else:
dtype_ = dtype If I now type What is the best way to solve this issue? Can one somehow detect if the Mapping is Simple MVCE where mypy raises: from __future__ import annotations
from numpy.typing import DTypeLike
from typing import Mapping
x: DTypeLike | Mapping[int, DTypeLike]
y: Mapping[int, DTypeLike]
if isinstance(x, Mapping):
y = x
else:
y = {1: x} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
I think the issue there is that Does this help? from __future__ import annotations
from typing import Any, Mapping, Union
from numpy.typing import DTypeLike
DTypeLikeMap = Union[Mapping[Any, DTypeLike], DTypeLike]
x: DTypeLikeMap
y: DTypeLikeMap
if isinstance(x, Mapping):
y = x
else:
# y = {1: x}
y = {"a": x} Weirdly it was getting confused by the |
Beta Was this translation helpful? Give feedback.
-
I guess I will go with a custom DTypeLike definition that excludes Mappings. This uses numpys internal definitions (many of them are still Any, but will change in future releases): from numpy.typing._dtype_like import _SupportsDType, _DTypeLikeNested, _ShapeLike, DType
DTypeLikeSave = Union[
DType[Any],
# default data type (float64)
None,
# array-scalar types and generic types
Type[Any],
# character codes, type strings or comma-separated fields, e.g., 'float64'
str,
# (flexible_dtype, itemsize)
Tuple[_DTypeLikeNested, int],
# (fixed_dtype, shape)
Tuple[_DTypeLikeNested, _ShapeLike],
# (base_dtype, new_dtype)
Tuple[_DTypeLikeNested, _DTypeLikeNested],
# because numpy does the same?
list[Any],
# anything with a dtype attribute
_SupportsDType[DType[Any]]
] |
Beta Was this translation helpful? Give feedback.
I guess I will go with a custom DTypeLike definition that excludes Mappings.
This uses numpys internal definitions (many of them are still Any, but will change in future releases):