Skip to content
Discussion options

You must be logged in to vote

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 to Manager (effectively discarding the fact it's a subclass), making the list a list[Manager]. Adding some variable annotations can help demonstrate the behaviour:

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.

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Murtagy
Comment options

Answer selected by Murtagy
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