Skip to content

Instantly share code, notes, and snippets.

@nrbnlulu
Last active May 12, 2024 08:22
Show Gist options
  • Save nrbnlulu/aeb318457b728d6fd108068bf7f5b1bb to your computer and use it in GitHub Desktop.
Save nrbnlulu/aeb318457b728d6fd108068bf7f5b1bb to your computer and use it in GitHub Desktop.
Co/Cont/In(variance)

Covariant

parent :< child
child :< parent
i.e (fn args)

def eat(anima: Animal): ...

eat(Dog())

def bark(dog: Dog): ...

bark(Animal())

Contravariant

parent :< child
child :< parent
i.e (return types):

def debug_animal_create(fn: Callable[[], Animal]) -> Animal:...

def get_dog() -> Dog: ...

def get_zebra() -> Zebra: ...


debug_animal_create(get_dog)  # Callable[[], Animal] :< Callable[[], Dog]
debug_animal_create(get_zebra)  # callable[[], Animal] :< Callable[[], Zebra]

def get_animal() -> Animal: ...

def debug_zebra_create(fn: Callable[[], Zebra]) -> Zebra:...

debug_zebra_create(get_animal) # ❌ Callable[[], Zebra] !:< Callable[[], Animal]

Invariant

parent :< child
child :< parent
i.e (mutable containers):

dogs = list[Dog] = [Dog()]

animals: list[Animals] = [Fish()]

animals.append(Dog()) # ✅  dog :< animal 

animals = dogs # ❌ list[Dog] !:< list[Animal]

dogs = animals # ❌ 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment