Convert an object into a Variable. Parameters ---------- obj : object Object to convert into a Variable. - If the object is already a Variable, return a shallow copy. - Otherwise, if the object has 'dims' and 'data' attributes, convert it into a new Va
(
obj: T_DuckArray | Any, name=None, auto_convert: bool = True
)
| 96 | |
| 97 | |
| 98 | def as_variable( |
| 99 | obj: T_DuckArray | Any, name=None, auto_convert: bool = True |
| 100 | ) -> Variable | IndexVariable: |
| 101 | """Convert an object into a Variable. |
| 102 | |
| 103 | Parameters |
| 104 | ---------- |
| 105 | obj : object |
| 106 | Object to convert into a Variable. |
| 107 | |
| 108 | - If the object is already a Variable, return a shallow copy. |
| 109 | - Otherwise, if the object has 'dims' and 'data' attributes, convert |
| 110 | it into a new Variable. |
| 111 | - If all else fails, attempt to convert the object into a Variable by |
| 112 | unpacking it into the arguments for creating a new Variable. |
| 113 | name : str, optional |
| 114 | If provided: |
| 115 | |
| 116 | - `obj` can be a 1D array, which is assumed to label coordinate values |
| 117 | along a dimension of this given name. |
| 118 | - Variables with name matching one of their dimensions are converted |
| 119 | into `IndexVariable` objects. |
| 120 | auto_convert : bool, optional |
| 121 | For internal use only! If True, convert a "dimension" variable into |
| 122 | an IndexVariable object (deprecated). |
| 123 | |
| 124 | Returns |
| 125 | ------- |
| 126 | var : Variable |
| 127 | The newly created variable. |
| 128 | |
| 129 | """ |
| 130 | from xarray.core.dataarray import DataArray |
| 131 | |
| 132 | # TODO: consider extending this method to automatically handle Iris and |
| 133 | if isinstance(obj, DataArray): |
| 134 | # extract the primary Variable from DataArrays |
| 135 | obj = obj.variable |
| 136 | |
| 137 | if isinstance(obj, Variable): |
| 138 | obj = obj.copy(deep=False) |
| 139 | elif isinstance(obj, tuple): |
| 140 | try: |
| 141 | dims_, data_, *attrs = obj |
| 142 | except ValueError as err: |
| 143 | raise ValueError( |
| 144 | f"Tuple {obj} is not in the form (dims, data[, attrs])" |
| 145 | ) from err |
| 146 | |
| 147 | if isinstance(data_, DataArray): |
| 148 | raise TypeError( |
| 149 | f"Variable {name!r}: Using a DataArray object to construct a variable is" |
| 150 | " ambiguous, please extract the data using the .data property." |
| 151 | ) |
| 152 | try: |
| 153 | obj = Variable(dims_, data_, *attrs) |
| 154 | except (TypeError, ValueError) as error: |
| 155 | raise error.__class__( |
searching dependent graphs…