2 ms·
You can already have exhaustiveness-checking by the type checker right now today. from enum import Enum from typing import NoReturn class Stuff(En
by Spivak 5y ago
You can already have exhaustiveness-checking by the type checker right now today.
from enum import Enum
from typing import NoReturn
class Stuff(Enum):
Cat = 1
Dog = 2
Bear = 3
def exhaustiveness_check(value: NoReturn) -> NoReturn:
raise AssertionError()
def do_thing(stuff: Stuff) -> None:
if stuff is Stuff.Cat:
print("meow")
elif stuff is Stuff.Dog:
print("woof")
else:
exhaustiveness_check(stuff)
And if you add a check for Bear it will validate it!
- _dain_ 5y agoOkay but what if I need something more than an enum? Like if the stuff parameter is of type "BaseThing", and there are only meant to be five subclasses of BaseThing to check. I would want the type checker to verify that I dealt with every case. But without sealed classes, it can't determine that some other code that subclasses from BaseThing is wrong.
- Spivak 5y agoAbsolutely! And since type checkers will likely never be able to implement support for __subclasscheck__ or __instancecheck__ the best we can ever do is annotations about the desired results of those methods. My only statement was that match isn't magic and you can do exhaustiveness checking (inasmuch as type checkers can detect it) without it.