| 13 | |
| 14 | |
| 15 | class DataVariables(Mapping[Hashable, "DataArray"]): |
| 16 | __slots__ = ("_dataset",) |
| 17 | |
| 18 | def __init__(self, dataset: "Dataset"): |
| 19 | self._dataset = dataset |
| 20 | |
| 21 | def __iter__(self) -> Iterator[Hashable]: |
| 22 | return ( |
| 23 | key |
| 24 | for key in self._dataset._variables |
| 25 | if key not in self._dataset._coord_names |
| 26 | ) |
| 27 | |
| 28 | def __len__(self) -> int: |
| 29 | length = len(self._dataset._variables) - len(self._dataset._coord_names) |
| 30 | assert length >= 0, "something is wrong with Dataset._coord_names" |
| 31 | return length |
| 32 | |
| 33 | def __contains__(self, key: Hashable) -> bool: |
| 34 | return key in self._dataset._variables and key not in self._dataset._coord_names |
| 35 | |
| 36 | def __getitem__(self, key: Hashable) -> "DataArray": |
| 37 | if key not in self._dataset._coord_names: |
| 38 | return self._dataset[key] |
| 39 | raise KeyError(key) |
| 40 | |
| 41 | def __repr__(self) -> str: |
| 42 | return formatting.data_vars_repr(self) |
| 43 | |
| 44 | @property |
| 45 | def variables(self) -> Mapping[Hashable, Variable]: |
| 46 | all_variables = self._dataset.variables |
| 47 | return Frozen({k: all_variables[k] for k in self}) |
| 48 | |
| 49 | @property |
| 50 | def dtypes(self) -> Frozen[Hashable, np.dtype]: |
| 51 | """Mapping from data variable names to dtypes. |
| 52 | |
| 53 | Cannot be modified directly, but is updated when adding new variables. |
| 54 | |
| 55 | See Also |
| 56 | -------- |
| 57 | Dataset.dtype |
| 58 | """ |
| 59 | return self._dataset.dtypes |
| 60 | |
| 61 | def _ipython_key_completions_(self): |
| 62 | """Provide method for the key-autocompletions in IPython.""" |
| 63 | return [ |
| 64 | key |
| 65 | for key in self._dataset._ipython_key_completions_() |
| 66 | if key not in self._dataset._coord_names |
| 67 | ] |