Literal values not bound to TypeVar as Literal values? #6454
Unanswered
ringohoffman
asked this question in
Q&A
Replies: 1 comment 3 replies
-
Possible solution is to add from __future__ import annotations
from typing import Any, Generic, TypeVar, overload
from typing import Literal as L, Literal
IntLiteral = Literal[1,2,3,4,5,6,7,8,9,10]
M_literal = TypeVar("M_literal", bound=IntLiteral)
N_literal = TypeVar("N_literal", bound=IntLiteral)
M = TypeVar("M", bound=int, covariant=True)
N = TypeVar("N", bound=int, covariant=True)
P = TypeVar("P", bound=int)
DtypeT = TypeVar("DtypeT")
class Matrix(Generic[DtypeT, N, M]):
def __init__(self, n: int, m: int, dt: DtypeT | None = None):
...
@overload
def __new__(cls, n: N_literal, m: M_literal, dt: DtypeT | None = None) -> Matrix[DtypeT, N_literal, M_literal]: ...
@overload
def __new__(cls, n: int, m: int, dt: DtypeT | None = None) -> Matrix[DtypeT, int, int]: ...
def __new__(cls, n: int, m: int, dt: DtypeT | None = None) -> Matrix[DtypeT, int, int]:
return super().__new__(cls)
@overload
def __matmul__(self: Matrix[DtypeT, N, L[1]], other: Matrix[DtypeT, N, P], /) -> Matrix[DtypeT, P, L[1]]:
...
@overload
def __matmul__(self: Matrix[DtypeT, N, M], other: Matrix[DtypeT, M, L[1]], /) -> Matrix[DtypeT, N, L[1]]:
...
@overload
def __matmul__(self: Matrix[DtypeT, N, M], other: Matrix[DtypeT, M, P], /) -> Matrix[DtypeT, N, P]:
...
def __matmul__(self, other: Any, /) -> Any:
...
m4x4 = Matrix(4, 4, float)
reveal_type(m4x4) # Type of "m4x4" is "Matrix[type[float], Literal[4], Literal[4]]" |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm trying to add matrix shape type checking to taichi. They have a
MatrixType
class which can be used to create a 2DMatrix
. The 2 shape parameters toMatrixType
,N
andM
, can be provided as literal integers, whichtaichi.math
actually does. But unless I explicitly declare aMatrixType
usingLiteral
,N
andM
are always inferred asint
, even when using literals... implicitly opting you out of static shape checking.I feel that it is unexpected and burdensome to have to manually declare the shape when you are already using a literal values to define the shape. Could the default instead be to use the
Literal
values?Beta Was this translation helpful? Give feedback.
All reactions