-
-
Save micimize/207317bfd633db91bc1afb05840a1f85 to your computer and use it in GitHub Desktop.
Demonstration of mutability and covariance inference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import List, Sequence, Dict, Mapping | |
from typing_extensions import reveal_type | |
class Animal: | |
pass | |
class Dog(Animal): | |
pass | |
class Cat(Animal): | |
pass | |
def mutate_list(d: List[Animal]): | |
pass | |
def no_mutate_list(d: Sequence[Animal]): | |
pass | |
dog_list = [Dog()] | |
catdog_list = [Cat(), Dog()] | |
print(reveal_type(dog_list)) # List[Dog] | |
print(reveal_type(catdog_list)) # List[Animal] | |
# error: Argument 1 to "mutate_list" has incompatible type "List[Dog]"; expected "List[Animal]" | |
# note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance | |
# note: Consider using "Sequence" instead, which is covariant | |
mutate_list(dog_list) | |
mutate_list(catdog_list) | |
no_mutate_list(dog_list) | |
def mutate_dict(d: Dict[str, Animal]): | |
pass | |
def no_mutate_dict(d: Mapping[str, Animal]): | |
pass | |
cat_dict = {"cat": Cat()} # Dict[str, Cat] | |
catdog_dict = {"cat": Cat(), "dog": Dog()} # Dict[str, Animal] | |
# error: Argument 1 to "mutate_dict" has incompatible type "Dict[str, Cat]"; expected "Dict[str, Animal]" | |
# note: "Dict" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance | |
# note: Consider using "Mapping" instead, which is covariant in the value type | |
mutate_dict(cat_dict) | |
mutate_dict(catdog_dict) | |
no_mutate_dict(cat_dict) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment