Is variance of List is documented correctly? #1300
|
https://mypy.readthedocs.io/en/stable/generics.html#variance-of-generic-types Documentation states that lists are invariant, although they act as covariant. I have reproduced the example of Managers and Employees the docs mentions And here are the results: If the List was invariant I would expect only middle one to be valid, |
Answered by
TeamSpen210
Nov 30, 2022
Replies: 1 comment 1 reply
|
List is invariant, the reason this works is that type checkers are smart enough to do bidirectional inference to find a solution. What it's doing is casting bosses: list[Boss] = [Boss()]
salaries(bosses, accountant_M) # Fails as expected
secret_boss: Manager = Boss() # Valid cast, it's a subclass.
salaries([secret_boss], accountant_M) # This works, because it's just an Manager here. |
1 reply
Answer selected by
Murtagy
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
List is invariant, the reason this works is that type checkers are smart enough to do bidirectional inference to find a solution. What it's doing is casting
BosstoManager(effectively discarding the fact it's a subclass), making the list alist[Manager]. Adding some variable annotations can help demonstrate the behaviour: