What type should I set instead of TYPE1 and TYPE2 for x, y values?
x: TYPE1 = list
y: TYPE2 = list[int]
For TYPE1 case, if I set
type T = int | str | bool
x: type[list[T]] = list
mypy returns no errors, but why everything is ok here if value - "list" has no type specified?
And for TYPE2 I have no idea what it should be set to
Ok, so I end up with
type TT = int | str | bool | float
type GenericIterableType[T: TT] = list[T] | tuple[T, ...] | set[T]
t: type[GenericIterableType[int] | GenericIterableType[str]] = list[str]
But is it possible to not repeat GenericIterableType for every type in TT ?
What type should I set instead of TYPE1 and TYPE2 for x, y values?
x: TYPE1 = list
y: TYPE2 = list[int]
For TYPE1 case, if I set
type T = int | str | bool
x: type[list[T]] = list
mypy returns no errors, but why everything is ok here if value - "list" has no type specified?
And for TYPE2 I have no idea what it should be set to
Ok, so I end up with
type TT = int | str | bool | float
type GenericIterableType[T: TT] = list[T] | tuple[T, ...] | set[T]
t: type[GenericIterableType[int] | GenericIterableType[str]] = list[str]
But is it possible to not repeat GenericIterableType for every type in TT ?
Share Improve this question edited Jan 30 at 15:13 sector119 asked Jan 29 at 20:59 sector119sector119 8961 gold badge8 silver badges13 bronze badges 7 | Show 2 more comments1 Answer
Reset to default 3mypy returns no errors, but why everything is ok here if value - "list" has no type specified?
Because the value is fine? Without reified generic, the value list
works for any type[list[X]]
you want. You can see that the type-checking works if you use x
: https://mypy-play/?mypy=latest&python=3.12&flags=no-warn-no-return%2Cwarn-redundant-casts%2Cwarn-return-any%2Cwarn-unreachable&gist=86ac2f94aff7b3f2f923162b9c9f8988
type T = int | str | bool
x: type[list[T]] = list
l1 = x()
l1.append(1)
l1.append("xxx")
l2 = x()
l2.append(None)
mypy triggers an error on the last line, because None
is not a valid value for a list[T]
.
Incidentally int | bool
is redundant, for historical reasons in Python bool
is a subtype of int
, so int | bool = int
.
And for TYPE2 I have no idea what it should be set to
type[list[int]]
, what else would it be?
mypy
absolutely cares about types – juanpa.arrivillaga Commented Jan 29 at 22:12mypy
explicitly, so they are using static type checking – juanpa.arrivillaga Commented Jan 29 at 22:12GenericIterableType
... if that's what you want, you should just usecollections.abc.Iterable
– juanpa.arrivillaga Commented Jan 30 at 16:16