Reason about Variance
Core idea
Variance describes assignability between parameterized types. A read-only Sequence of dogs can serve as a Sequence of animals (covariance); a mutable list of dogs cannot safely serve as a list of animals (invariance). A callable accepting any animal can serve where a callable accepting a dog is required (contravariance of parameters). These are static contracts.
from collections.abc import Sequenceclass Animal: passclass Dog(Animal): passdef count(items: Sequence[Animal])->int: return len(items)dogs: list[Dog] = [Dog(), Dog()]print(count(dogs))Reading the sequence does not insert a different animal.
Accept a wider input
from collections.abc import Callableclass Animal: passclass Dog(Animal): passdef describe(a:Animal)->str: return 'animal'def handle(fn:Callable[[Dog],str])->str: return fn(Dog())print(handle(describe))A handler for all animals can handle a dog.
Common mistake
A function accepting list[Animal] could append a cat. Do not pass list[Dog] to it; use Sequence[Animal] when mutation is unnecessary.
Practice
Create Animal, Dog and Cat classes. Check a read-only function and a mutable function against list[Dog] in a static checker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Variance
Check your understanding of variance.
What is printed?
class A: passclass B(A): passprint(isinstance(B(), A))What is printed?
def f(xs): xs.append(3)x=[1,2]f(x)print(x)Which interface is covariant in its element type?
Where is Callable parameter variance contravariant?