-
When running (latest, for 3.12) mypy check on the example below only the second instance raises the error from typing import TypeVar, Generic
T = TypeVar("T", int, bytes)
class AA[T]:
def __init__(self, arg: T):
self.arg: T = arg
class BB(Generic[T]):
def __init__(self, arg: T):
self.arg: T = arg
if __name__ == "__main__":
aa = AA("aa")
bb = BB("bb") |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I think the behaviour you're witnessing is correct, because the PEP 695 syntax introduces a new annotation scope. In other words, The You can think of your example as if it was roughly equivalent to the following: from typing import TypeVar, Generic
T = TypeVar("T", int, bytes)
def _aa():
T = TypeVar("T")
class AA(Generic[T]):
def __init__(self, arg: T):
self.arg: T = arg
return AA
AA = _aa()
del _aa
class BB(Generic[T]):
def __init__(self, arg: T):
self.arg: T = arg
if __name__ == "__main__":
aa = AA("aa")
bb = BB("bb") I think the PEP 695 syntax you're looking for is this: class AA[T: (int, bytes)]:
def __init__(self, arg: T):
self.arg: T = arg
if __name__ == "__main__":
aa = AA("aa") and as you can see in the mypy playground, mypy correctly reports the error now. Note This also means that if you are currently sharing a single |
Beta Was this translation helpful? Give feedback.
I think the behaviour you're witnessing is correct, because the PEP 695 syntax introduces a new annotation scope.
In other words,
T
inclass BB(Generic[T]): ...
(with the old syntax) is indeed a reference toT = TypeVar("T", int, bytes)
, but theT
inside the body ofAA
is a different symbol.The
class AA[T]:
declaration defines a newTypeVar
that, because it's also namedT
, shadows the one defined at module scope - and because this newT
does not have the(int, bytes)
bound, the instantiationAA("aa")
type checks.You can think of your example as if it was roughly equivalent to the following: