Hacker News new | ask | show | jobs
by stayfrosty420 1113 days ago
@dataclass is the new final
1 comments

Does 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.
Yes, that's what @typing.final is: 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!")
It'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.h...

Thanks for this trick for exhaustiveness checking, I've just been putting

  assert False, "This is unreachable."
in my code until now.