-
from abc import ABC
from dataclasses import dataclass
@dataclass(frozen=True, kw_only=True, slots=True)
class Balance(ABC):
value: int
@dataclass(frozen=True, kw_only=True, slots=True)
class USD(Balance):
pass
@dataclass(frozen=True, kw_only=True, slots=True)
class EUR(Balance):
pass
@dataclass(frozen=True, kw_only=True, slots=True)
class Account[BalanceType: Balance](ABC):
balance: BalanceType
@dataclass(frozen=True, kw_only=True, slots=True)
class USDAccount(Account[USD]):
pass
@dataclass(frozen=True, kw_only=True, slots=True)
class EURAccount(Account[EUR]):
pass
def create[BalanceType: Balance](balance: BalanceType) -> Account[BalanceType]:
match balance:
case USD():
return USDAccount(balance=balance)
case EUR():
return EURAccount(balance=balance)
case _:
assert False Pyright gives me an error:
If I understand it correctly, by making everything frozen, it should automatically be covariant in |
Beta Was this translation helpful? Give feedback.
Answered by
erictraut
Dec 5, 2024
Replies: 1 comment 3 replies
-
The problem is not with variance. The issue is that when you call You can fix this by making @dataclass(frozen=True, kw_only=True, slots=True)
class USDAccount[T: USD](Account[T]):
test: int = 4
@dataclass(frozen=True, kw_only=True, slots=True)
class EURAccount[T: EUR](Account[T]):
pass |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
rdong8
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The problem is not with variance. The issue is that when you call
USDAccount(balance=balance)
, the resulting type isUSDAccount
. The information about the type variable has been lost, and this type is no longer assignable toAccount[BalanceType]
. Not surprisingly, mypy generates the same error here.You can fix this by making
USDAccount
andEURAccount
generic.