Element types¶
The element type of an array is what NumPy calls its dtype: float32,
int64, bool. The functions on this page answer with the element type of a
result, given the element types of the operands.
| Function | NumPy |
|---|---|
result_type |
np.result_type |
can_cast |
np.can_cast with safe casting |
ufunc_dtype, ufunc_dtypes |
The element type an element-wise ufunc returns |
reduce_dtype |
The element type a reduction returns |
The fourteen types¶
Fourteen element types are covered. DTYPES lists them by their NumPy names:
>>> sr.DTYPES
('bool', 'int8', 'int16', 'int32', 'int64',
'uint8', 'uint16', 'uint32', 'uint64',
'float16', 'float32', 'float64', 'complex64', 'complex128')
Anything else answers Unknown. That includes datetime64, timedelta64,
longdouble, object, strings and structured types.
Writing an element type¶
A function on this page accepts an element type in any of these ways:
- its full NumPy name,
"float32", with or without a leadingnumpy.; - a NumPy dtype or scalar type,
np.dtype("float32")ornp.float32, when NumPy is installed; - one of the Python types
int,float,complexorbool, which stands for a Python number among the operands.
NumPy objects are recognised by their name, so shaperules does not import
NumPy to read them. Short codes and aliases such as "f4" and "double" are
not read.
>>> import numpy as np
>>> sr.result_type(np.float32, np.dtype("int8"), "numpy.int16")
Known(value='float32')
>>> sr.result_type("f4")
Unknown(reason="element type 'f4' is not covered", likely=None)
result_type¶
result_type(*operands) is np.result_type: the element type the operands
promote to. Promotion is how NumPy picks one type that can hold the values of
several.
>>> sr.result_type("int8", "int32").value
'int32'
>>> sr.result_type("int8", "uint8").value
'int16'
>>> sr.result_type("int32", "float32").value
'float64'
>>> sr.result_type("float32", "complex64").value
'complex64'
A signed and an unsigned integer of 64 bits have no integer type that holds
both. NumPy promotes them to float64, and so does result_type:
Python numbers¶
NumPy 2 treats a Python number among the operands differently from an array.
The rule is NEP 50, the NumPy enhancement proposal that set the promotion
rules of NumPy 2. Element types come in kinds, from lowest to highest:
boolean, integer, float and complex. A Python int, float or complex is a
weak operand. It has no element type of its own and takes the type of the
array it meets, as long as that type is of its kind or a higher one. Write the
Python number as its type.
>>> sr.result_type("float32", float).value
'float32'
>>> sr.result_type("uint8", int).value
'uint8'
>>> sr.result_type("complex64", float).value
'complex64'
A Python number of a higher kind than the array lifts the result to that kind:
>>> sr.result_type("int8", float).value
'float64'
>>> sr.result_type("float32", complex).value
'complex64'
>>> sr.result_type("float64", complex).value
'complex128'
With Python numbers alone, the answer is the default type of the highest kind among them:
Python's bool is not weak. NumPy treats True as a value of its own bool
type, and so does result_type.
More than two operands¶
np.result_type of three or more types is not what you get by promoting them
two at a time. It is the smallest type every operand casts to safely, worked
out over all of them at once.
Folding pair by pair gives a wider answer. int8 with uint8 is int16, and
int16 with float16 is float32:
>>> pair = sr.result_type("int8", "uint8").value
>>> pair
'int16'
>>> sr.result_type(pair, "float16").value
'float32'
So pass every operand to one call of result_type. The story of how this was
found is in Checked against NumPy.
can_cast¶
can_cast(source, target) is np.can_cast(source, target, "safe"): whether
NumPy converts one element type to the other under its safe casting rule.
>>> sr.can_cast("int8", "int16")
Known(value=True)
>>> sr.can_cast("uint8", "int8")
Known(value=False)
>>> sr.can_cast("float64", "float32")
Known(value=False)
The answer is NumPy's, and NumPy's safe rule lets some integers through to a float type that cannot hold every one of their values exactly:
A Python number type answers Unknown. np.can_cast in NumPy 2 does not
take a Python number either:
ufunc_dtype¶
A ufunc is one of NumPy's element-by-element functions, such as np.add,
np.sqrt or np.less.
ufunc_dtype(name, *operands) is the element
type the ufunc returns for operands of the types given. The name is the
ufunc's NumPy name.
>>> sr.ufunc_dtype("add", "int8", "uint8").value
'int16'
>>> sr.ufunc_dtype("true_divide", "int32", "int32").value
'float64'
>>> sr.ufunc_dtype("less", "float32", "int64").value
'bool'
>>> sr.ufunc_dtype("sqrt", "int8").value
'float16'
>>> sr.ufunc_dtype("absolute", "complex64").value
'float32'
The result is not always the promoted type of the operands, as the last four show. Each ufunc has its own list of loops inside NumPy, and the answers here are read from tables that were asked of NumPy itself. Design says why.
A Python number is written as its type, as in result_type:
>>> sr.ufunc_dtype("multiply", "float32", float).value
'float32'
>>> sr.ufunc_dtype("add", "int8", float).value
'float64'
Refusals¶
Where NumPy has no loop for the types, it raises TypeError, and the answer
is Refused with the kind no-loop:
>>> answer = sr.ufunc_dtype("subtract", "bool", "bool")
>>> answer.refusal.kind, answer.refusal.raises
('no-loop', 'TypeError')
>>> print(answer.refusal.message)
subtract has no loop for bool, bool
>>> sr.ufunc_dtype("floor", "complex64").refusal.kind
'no-loop'
>>> sr.ufunc_dtype("bitwise_and", "float32", "float32").refusal.kind
'no-loop'
Ufuncs with two outputs¶
A few ufuncs return two arrays. ufunc_dtypes answers with a tuple, one
element type per output. ufunc_dtype answers with the first.
>>> sr.ufunc_dtypes("divmod", "int8", "int16").value
('int16', 'int16')
>>> sr.ufunc_dtypes("frexp", "float32").value
('float32', 'int32')
>>> sr.ufunc_dtypes("add", "int8", "int8").value
('int8',)
Which ufuncs¶
Every element-wise ufunc of one or two inputs in NumPy's main namespace is in
the tables, under every public name it has. divide and true_divide are
both there, and so are abs and absolute. shaperules.dtypes.ufunc_names()
lists them. The tables shipped with 0.1 were generated from NumPy 2.5.5 and
hold 102 names.
>>> names = sr.dtypes.ufunc_names()
>>> len(names)
102
>>> names[:6]
('abs', 'absolute', 'acos', 'acosh', 'add', 'arccos')
A name that is not in the tables answers Unknown. That includes the
generalized ufuncs, such as matmul, whose operands are whole matrices and
not single elements. Giving a ufunc the wrong number of operands is an error
in the call and raises:
>>> sr.ufunc_dtype("matmul", "int8", "int8")
Unknown(reason="ufunc 'matmul' is not covered", likely=None)
>>> sr.ufunc_dtype("add", "int8")
Traceback (most recent call last):
...
ValueError: add takes 2 operands, 1 given
reduce_dtype¶
reduce_dtype(name, dtype) is the element type a reduction or a running
total returns, for the function's default arguments. It does not model the
dtype= argument.
>>> sr.reduce_dtype("sum", "int8").value
'int64'
>>> sr.reduce_dtype("sum", "uint8").value
'uint64'
>>> sr.reduce_dtype("mean", "int32").value
'float64'
>>> sr.reduce_dtype("mean", "float32").value
'float32'
>>> sr.reduce_dtype("std", "complex64").value
'float32'
>>> sr.reduce_dtype("argmax", "float32").value
'int64'
>>> sr.reduce_dtype("any", "float32").value
'bool'
np.sum of small integers returns a 64-bit integer, which is why the first
answer is not int8.
Sixteen functions are covered:
>>> sr.dtypes.reduction_names()
('all', 'any', 'argmax', 'argmin', 'count_nonzero', 'cumprod', 'cumsum', 'max',
'mean', 'median', 'min', 'prod', 'ptp', 'std', 'sum', 'var')
np.ptp of booleans is a TypeError in NumPy. It is the one refusal among
the reductions:
The operand is the element type of an array. A Python number type answers
Unknown.
Shape and element type together¶
The two halves of the library are independent. A client that wants both for
one call asks both. For a / b, with a an int32 array of shape
(batch, 1, 3) and b a float32 array of shape (n, 3):
>>> shape = sr.broadcast(("batch", 1, 3), ("n", 3))
>>> dtype = sr.ufunc_dtype("true_divide", "int32", "float32")
>>> sr.fmt_shape(shape.unwrap()), dtype.unwrap()
('(batch, n, 3)', 'float64')
For a.sum(axis=1) with a a uint8 array of shape (batch, n):
>>> shape = sr.reduce(("batch", "n"), axis=1)
>>> dtype = sr.reduce_dtype("sum", "uint8")
>>> sr.fmt_shape(shape.unwrap()), dtype.unwrap()
('(batch,)', 'uint64')
What is not modelled¶
One thing about element types depends on a value and is not modelled. A
Python integer that does not fit the array's type raises OverflowError in
NumPy: np.uint8(1) + 300 is an error, although uint8 with a Python int
is uint8. shaperules sees types only and answers uint8:
The integer results int64 and uint64 in the tables are those of a 64-bit
platform, where NumPy's default integer has 64 bits. The other limits are in
Limitations and roadmap.