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, |
Beta Was this translation helpful? Give feedback.
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. |
Beta Was this translation helpful? Give feedback.
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
Boss
toManager
(effectively discarding the fact it's a subclass), making the list alist[Manager]
. Adding some variable annotations can help demonstrate the behaviour: