Skip to content

Trouble with type variance and factory functions #9551

Answered by erictraut
rdong8 asked this question in Q&A
Discussion options

You must be logged in to vote

The problem is not with variance. The issue is that when you call USDAccount(balance=balance), the resulting type is USDAccount. The information about the type variable has been lost, and this type is no longer assignable to Account[BalanceType]. Not surprisingly, mypy generates the same error here.

You can fix this by making USDAccount and EURAccount generic.

@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

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@rdong8
Comment options

@erictraut
Comment options

@rdong8
Comment options

Answer selected by rdong8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants