MCPcopy Index your code
hub / github.com/pydata/xarray / as_variable

Function as_variable

xarray/core/variable.py:98–189  ·  view source on GitHub ↗

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
)

Source from the content-addressed store, hash-verified

96
97
98def 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__(

Callers 10

_validate_indexersMethod · 0.90
maybe_variableMethod · 0.90
__init__Method · 0.90
_infer_coords_and_dimsFunction · 0.90
_check_data_shapeFunction · 0.90
subsetMethod · 0.90
test_as_variableMethod · 0.90

Calls 7

to_index_variableMethod · 0.95
emit_user_level_warningFunction · 0.90
typeFunction · 0.85
as_compatible_dataFunction · 0.85
VariableClass · 0.70
copyMethod · 0.45

Tested by 1

test_as_variableMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…