array-api icon indicating copy to clipboard operation
array-api copied to clipboard

Disallowed typing in `linalg.vector_norm`

Open lucascolley opened this issue 1 year ago • 4 comments

Spec:

ord: int | float | ~typing.Literal[inf, -inf] = 2

Stubs:

ord: Union[int, float, Literal[inf, -inf]] = 2

Literals docs

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: https://github.com/python/typing/issues/1160


I don't know if anything can be done, and this was probably done deliberately, but useful to have an issue nonetheless.

lucascolley avatar Jul 01 '24 11:07 lucascolley

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.

asmeurer avatar Jul 01 '24 17:07 asmeurer

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

pyright playground link

jorenham avatar Aug 19 '24 01:08 jorenham

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.

asmeurer avatar Sep 03 '24 21:09 asmeurer

FYI, enum values are allowed in typing.Literal

jorenham avatar Sep 04 '24 08:09 jorenham

let's close this issue, as I don't think there is anything actionable right now.

The desirable solution long-term is to overhaul all 'pseudo-typing' in the spec with whatever is most readable (which can deviate from typing spec syntax), and have proper typing live in array-api-typing. That goes above and beyond the scope of this issue, though.

lucascolley avatar Jun 16 '25 14:06 lucascolley