Created
October 31, 2026 19:32
-
-
Save mypy-play/02b87ea41dc199ac0c8504d9e14d75d8 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
This file contains hidden or 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 collections.abc import Callable | |
| class Animal: ... | |
| class Dog(Animal): | |
| def bark(self) -> None: print("woof") | |
| class Cat(Animal): ... | |
| class Handler[T]: | |
| def __init__(self, cb: Callable[[T], None]) -> None: | |
| self.cb = cb | |
| def use(h: Handler[Dog]) -> None: | |
| h.cb = lambda d: d.bark() | |
| ha = Handler[Animal](lambda a: print(a)) | |
| use(ha) # mypy: no error (Handler[Animal] accepted as Handler[Dog]) | |
| ha.cb(Cat()) # Runtime: AttributeError: 'Cat' object has no attribute 'bark' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment