3 ms·
@dataclass is the new final
by stayfrosty420 3y ago
@dataclass is the new final
- _dain_ 3y agoDoes the type system let you express that a class shouldn't be subclassed? I remember this possibility was mentioned in a PEP and got deferred. It would be really useful with the new match/case pattern matching feature, because then you could have proper sum types, and mypy could enforce exhaustiveness. AFAIK you have to do a workaround with a "assert False" or similar at the end.
- nerdponx 3y agoYes, that's what @typing.final is: https://docs.python.org/3/library/typing.html#typing.final https://docs.python.org/3/library/typing.html#typing.final But that's only checked by the type checker. At runtime you still need to do something like this to prevent subclassing: class DontSubclassMe: def __init_subclass__(self): raise TypeError("Don't subclass me!")
- hfhdjdks 3y agoIt's not what you were asking for (class that can't be subclassed), but `typing` has an `assert_never` to check exhaustiveness: https://typing.readthedocs.io/en/latest/source/unreachable.html https://typing.readthedocs.io/en/latest/source/unreachable.h...
- nerdponx 3y agoThanks for this trick for exhaustiveness checking, I've just been putting assert False, "This is unreachable." in my code until now.