Skip to content

Commit 1757dff

Browse files
crusaderkymax-sixty
authored andcommitted
More annotations in Dataset (#3112)
* Let mypy discover xarray typing hints * Docs tweak * More annotations in Dataset * Fix Python 3.5-specific check for OrderedDict * typing in merge * broadcast_like typing tweaks * Changed redundant x: Optional[MyType] = None to x: MyType = None * flake8 * What's New
1 parent e520534 commit 1757dff

File tree

10 files changed

+415
-237
lines changed

10 files changed

+415
-237
lines changed

doc/whats-new.rst

+9-1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ New functions/methods
2828
By `Deepak Cherian <https://github.com/dcherian>`_ and `David Mertz
2929
<http://github.com/DavidMertz>`_.
3030

31+
- The xarray package is now discoverably by mypy (although typing hints
32+
coverage is not complete yet). mypy users can now remove from their setup.cfg
33+
the lines::
34+
35+
[mypy-xarray]
36+
ignore_missing_imports = True
37+
38+
By `Guido Imperiale <https://github.com/crusaderky>`_
39+
3140
Enhancements
3241
~~~~~~~~~~~~
3342

@@ -70,7 +79,6 @@ New functions/methods
7079
(:issue:`3026`).
7180
By `Julia Kent <https://github.com/jukent>`_.
7281

73-
7482
Enhancements
7583
~~~~~~~~~~~~
7684

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,4 +104,4 @@
104104
tests_require=TESTS_REQUIRE,
105105
url=URL,
106106
packages=find_packages(),
107-
package_data={'xarray': ['tests/data/*']})
107+
package_data={'xarray': ['py.typed', 'tests/data/*']})

xarray/core/alignment.py

+25-8
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,16 @@
33
import warnings
44
from collections import OrderedDict, defaultdict
55
from contextlib import suppress
6-
from typing import Any, Mapping, Optional, Tuple
6+
from typing import (
7+
Any,
8+
Dict,
9+
Hashable,
10+
Mapping,
11+
Optional,
12+
Tuple,
13+
Union,
14+
TYPE_CHECKING,
15+
)
716

817
import numpy as np
918
import pandas as pd
@@ -13,6 +22,10 @@
1322
from .utils import is_dict_like, is_full_slice
1423
from .variable import IndexVariable, Variable
1524

25+
if TYPE_CHECKING:
26+
from .dataarray import DataArray
27+
from .dataset import Dataset
28+
1629

1730
def _get_joiner(join):
1831
if join == 'outer':
@@ -169,8 +182,8 @@ def deep_align(objects, join='inner', copy=True, indexes=None,
169182
170183
This function is not public API.
171184
"""
172-
from .dataarray import DataArray
173-
from .dataset import Dataset
185+
from .dataarray import DataArray # noqa: F811
186+
from .dataset import Dataset # noqa: F811
174187

175188
if indexes is None:
176189
indexes = {}
@@ -222,7 +235,10 @@ def is_alignable(obj):
222235
return out
223236

224237

225-
def reindex_like_indexers(target, other):
238+
def reindex_like_indexers(
239+
target: Union['DataArray', 'Dataset'],
240+
other: Union['DataArray', 'Dataset'],
241+
) -> Dict[Hashable, pd.Index]:
226242
"""Extract indexers to align target with other.
227243
228244
Not public API.
@@ -236,7 +252,8 @@ def reindex_like_indexers(target, other):
236252
237253
Returns
238254
-------
239-
Dict[Any, pandas.Index] providing indexes for reindex keyword arguments.
255+
Dict[Hashable, pandas.Index] providing indexes for reindex keyword
256+
arguments.
240257
241258
Raises
242259
------
@@ -310,7 +327,7 @@ def reindex_variables(
310327
new_indexes : OrderedDict
311328
Dict of indexes associated with the reindexed variables.
312329
"""
313-
from .dataarray import DataArray
330+
from .dataarray import DataArray # noqa: F811
314331

315332
# create variables for the new dataset
316333
reindexed = OrderedDict() # type: OrderedDict[Any, Variable]
@@ -407,8 +424,8 @@ def _get_broadcast_dims_map_common_coords(args, exclude):
407424

408425
def _broadcast_helper(arg, exclude, dims_map, common_coords):
409426

410-
from .dataarray import DataArray
411-
from .dataset import Dataset
427+
from .dataarray import DataArray # noqa: F811
428+
from .dataset import Dataset # noqa: F811
412429

413430
def _set_dims(var):
414431
# Add excluded dims to a copy of dims_map

xarray/core/common.py

+17-17
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from textwrap import dedent
44
from typing import (
55
Any, Callable, Hashable, Iterable, Iterator, List, Mapping, MutableMapping,
6-
Optional, Tuple, TypeVar, Union)
6+
Tuple, TypeVar, Union)
77

88
import numpy as np
99
import pandas as pd
@@ -101,7 +101,7 @@ def __int__(self: Any) -> int:
101101
def __complex__(self: Any) -> complex:
102102
return complex(self.values)
103103

104-
def __array__(self: Any, dtype: Optional[DTypeLike] = None) -> np.ndarray:
104+
def __array__(self: Any, dtype: DTypeLike = None) -> np.ndarray:
105105
return np.asarray(self.values, dtype=dtype)
106106

107107
def __repr__(self) -> str:
@@ -448,7 +448,7 @@ def pipe(self, func: Union[Callable[..., T], Tuple[Callable[..., T], str]],
448448
return func(self, *args, **kwargs)
449449

450450
def groupby(self, group, squeeze: bool = True,
451-
restore_coord_dims: Optional[bool] = None):
451+
restore_coord_dims: bool = None):
452452
"""Returns a GroupBy object for performing grouped operations.
453453
454454
Parameters
@@ -501,7 +501,7 @@ def groupby(self, group, squeeze: bool = True,
501501
def groupby_bins(self, group, bins, right: bool = True, labels=None,
502502
precision: int = 3, include_lowest: bool = False,
503503
squeeze: bool = True,
504-
restore_coord_dims: Optional[bool] = None):
504+
restore_coord_dims: bool = None):
505505
"""Returns a GroupBy object for performing grouped operations.
506506
507507
Rather than using all unique values of `group`, the values are discretized
@@ -557,8 +557,8 @@ def groupby_bins(self, group, bins, right: bool = True, labels=None,
557557
'include_lowest':
558558
include_lowest})
559559

560-
def rolling(self, dim: Optional[Mapping[Hashable, int]] = None,
561-
min_periods: Optional[int] = None, center: bool = False,
560+
def rolling(self, dim: Mapping[Hashable, int] = None,
561+
min_periods: int = None, center: bool = False,
562562
**window_kwargs: int):
563563
"""
564564
Rolling window object.
@@ -621,7 +621,7 @@ def rolling(self, dim: Optional[Mapping[Hashable, int]] = None,
621621

622622
def rolling_exp(
623623
self,
624-
window: Optional[Mapping[Hashable, int]] = None,
624+
window: Mapping[Hashable, int] = None,
625625
window_type: str = 'span',
626626
**window_kwargs
627627
):
@@ -658,7 +658,7 @@ def rolling_exp(
658658

659659
return self._rolling_exp_cls(self, window, window_type)
660660

661-
def coarsen(self, dim: Optional[Mapping[Hashable, int]] = None,
661+
def coarsen(self, dim: Mapping[Hashable, int] = None,
662662
boundary: str = 'exact',
663663
side: Union[str, Mapping[Hashable, str]] = 'left',
664664
coord_func: str = 'mean',
@@ -721,11 +721,11 @@ def coarsen(self, dim: Optional[Mapping[Hashable, int]] = None,
721721
self, dim, boundary=boundary, side=side,
722722
coord_func=coord_func)
723723

724-
def resample(self, indexer: Optional[Mapping[Hashable, str]] = None,
725-
skipna=None, closed: Optional[str] = None,
726-
label: Optional[str] = None,
727-
base: int = 0, keep_attrs: Optional[bool] = None,
728-
loffset=None, restore_coord_dims: Optional[bool] = None,
724+
def resample(self, indexer: Mapping[Hashable, str] = None,
725+
skipna=None, closed: str = None,
726+
label: str = None,
727+
base: int = 0, keep_attrs: bool = None,
728+
loffset=None, restore_coord_dims: bool = None,
729729
**indexer_kwargs: str):
730730
"""Returns a Resample object for performing resampling operations.
731731
@@ -1003,7 +1003,7 @@ def __getitem__(self, value):
10031003
raise NotImplementedError
10041004

10051005

1006-
def full_like(other, fill_value, dtype: Optional[DTypeLike] = None):
1006+
def full_like(other, fill_value, dtype: DTypeLike = None):
10071007
"""Return a new object with the same shape and type as a given object.
10081008
10091009
Parameters
@@ -1044,7 +1044,7 @@ def full_like(other, fill_value, dtype: Optional[DTypeLike] = None):
10441044

10451045

10461046
def _full_like_variable(other, fill_value,
1047-
dtype: Optional[DTypeLike] = None):
1047+
dtype: DTypeLike = None):
10481048
"""Inner function of full_like, where other must be a variable
10491049
"""
10501050
from .variable import Variable
@@ -1061,13 +1061,13 @@ def _full_like_variable(other, fill_value,
10611061
return Variable(dims=other.dims, data=data, attrs=other.attrs)
10621062

10631063

1064-
def zeros_like(other, dtype: Optional[DTypeLike] = None):
1064+
def zeros_like(other, dtype: DTypeLike = None):
10651065
"""Shorthand for full_like(other, 0, dtype)
10661066
"""
10671067
return full_like(other, 0, dtype)
10681068

10691069

1070-
def ones_like(other, dtype: Optional[DTypeLike] = None):
1070+
def ones_like(other, dtype: DTypeLike = None):
10711071
"""Shorthand for full_like(other, 1, dtype)
10721072
"""
10731073
return full_like(other, 1, dtype)

xarray/core/computation.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -683,7 +683,7 @@ def apply_array_ufunc(func, *args, dask='forbidden'):
683683
def apply_ufunc(
684684
func: Callable,
685685
*args: Any,
686-
input_core_dims: Optional[Sequence[Sequence]] = None,
686+
input_core_dims: Sequence[Sequence] = None,
687687
output_core_dims: Optional[Sequence[Sequence]] = ((),),
688688
exclude_dims: AbstractSet = frozenset(),
689689
vectorize: bool = False,
@@ -693,8 +693,8 @@ def apply_ufunc(
693693
keep_attrs: bool = False,
694694
kwargs: Mapping = None,
695695
dask: str = 'forbidden',
696-
output_dtypes: Optional[Sequence] = None,
697-
output_sizes: Optional[Mapping[Any, int]] = None
696+
output_dtypes: Sequence = None,
697+
output_sizes: Mapping[Any, int] = None
698698
) -> Any:
699699
"""Apply a vectorized function for unlabeled arrays on xarray objects.
700700

0 commit comments

Comments
 (0)