Disallowed typing in `linalg.vector_norm`
lucascolley opened this issue ยท 4 comments
Spec:
ord: int | float | ~typing.Literal[inf, -inf] = 2
ord: Union[int, float, Literal[inf, -inf]] = 2
The following are provisionally disallowed for simplicity. We can consider allowing them in the future.
- Floats: e.g. Literal[3.14]. Representing Literals of infinity or NaN in a clean way is tricky; real-world APIs are unlikely to vary their behavior based on a float parameter.
A relevant issue: python/typing#1160
I don't know if anything can be done, and this was probably done deliberately, but useful to have an issue nonetheless.
Yes, this is a known issue. There are some instances where the Python typing rules disallow certain things and we've opted to keep the annotations accurate in those cases. Implementations may need to adjust them until the upstream typing rules can be fixed.
float('inf')
and float('-inf')
are both assignable to the float
type, so why not just use ord: int | float
?
To illustrate
VectorOrder: typing.TypeAlias = int | float
orf: VectorOrder = float('inf') # no problem
That probably make sense for vector_norm, which actually accepts any float value (other than nan) https://data-apis.org/array-api/latest/extensions/generated/array_api.linalg.vector_norm.html#vector-norm
For matrix_norm
, it says float
, but it actually only supports integers and inf and -inf. A more accurate type description would be int | Literal[inf, -inf, 'fro', 'nuc']
https://data-apis.org/array-api/latest/extensions/generated/array_api.linalg.matrix_norm.html#matrix-norm
In any case, it probably is better to just loosen the typing here so that it can work with typing machinery. The actual set of allowed inputs is not representable by Python's typing rules, but it is spelled out in the standard text.
FYI, enum
values are allowed in typing.Literal