MCPcopy Create free account
hub / github.com/numpy/numpy / _promote_scalar

Method _promote_scalar

numpy/array_api/_array_object.py:172–220  ·  view source on GitHub ↗

Returns a promoted version of a Python scalar appropriate for use with operations on self. This may raise an OverflowError in cases where the scalar is an integer that is too large to fit in a NumPy integer dtype, or TypeError when the scalar type is incompa

(self, scalar)

Source from the content-addressed store, hash-verified

170
171 # Helper function to match the type promotion rules in the spec
172 def _promote_scalar(self, scalar):
173 """
174 Returns a promoted version of a Python scalar appropriate for use with
175 operations on self.
176
177 This may raise an OverflowError in cases where the scalar is an
178 integer that is too large to fit in a NumPy integer dtype, or
179 TypeError when the scalar type is incompatible with the dtype of self.
180 """
181 # Note: Only Python scalar types that match the array dtype are
182 # allowed.
183 if isinstance(scalar, bool):
184 if self.dtype not in _boolean_dtypes:
185 raise TypeError(
186 "Python bool scalars can only be promoted with bool arrays"
187 )
188 elif isinstance(scalar, int):
189 if self.dtype in _boolean_dtypes:
190 raise TypeError(
191 "Python int scalars cannot be promoted with bool arrays"
192 )
193 if self.dtype in _integer_dtypes:
194 info = np.iinfo(self.dtype)
195 if not (info.min <= scalar <= info.max):
196 raise OverflowError(
197 "Python int scalars must be within the bounds of the dtype for integer arrays"
198 )
199 # int + array(floating) is allowed
200 elif isinstance(scalar, float):
201 if self.dtype not in _floating_dtypes:
202 raise TypeError(
203 "Python float scalars can only be promoted with floating-point arrays."
204 )
205 elif isinstance(scalar, complex):
206 if self.dtype not in _complex_floating_dtypes:
207 raise TypeError(
208 "Python complex scalars can only be promoted with complex floating-point arrays."
209 )
210 else:
211 raise TypeError("'scalar' must be a Python scalar")
212
213 # Note: scalars are unconditionally cast to the same dtype as the
214 # array.
215
216 # Note: the spec only specifies integer-dtype/int promotion
217 # behavior for integers within the bounds of the integer dtype.
218 # Outside of those bounds we use the default NumPy behavior (either
219 # cast or raise OverflowError).
220 return Array._new(np.array(scalar, self.dtype))
221
222 @staticmethod
223 def _normalize_two_args(x1, x2) -> Tuple[Array, Array]:

Callers 1

_check_allowed_dtypesMethod · 0.95

Calls 1

_newMethod · 0.80

Tested by

no test coverage detected