2

How might I get the benefits of scala's sealed class in python? That is, to make it possible to subclass a class only in the module in which it's defined.

Note not a dupe of this post. C# sealed is equivalent to scala's final.

An example of where I might want this is to define an array type, and specify in that type what its shape is as follows

from typing import final, TypeVar, Generic
from abc import ABC, abstractmethod

S = TypeVar('S', bound=Shape)


class Array(ABC, Generic[S]):
    @abstractmethod
    def shape(self) -> S:
        pass


class Shape(ABC):  # how to make this sealed, or similar?
    pass


@final
class Shape1(Shape):
    pass


@final
class Shape2(Shape):
    pass


def fn(arr: Array[Shape2]):
    # some calculation that requires it to be a rank-2 array

As it is, someone can inherit from Shape and make their own rank 2 shape, which wouldn't be accepted by fn, even though it's valid (sure it's not necessarily a good idea to do that, but users can do what they like).

Other examples are making proper enums. I know there isn't pattern matching, but I imagine it would be confusing to define an Either type and for someone to make a third subclass.

joel
  • 6,359
  • 2
  • 30
  • 55
  • 1
    @jonrsharpe c# sealed is different from scala sealed afaik – joel Nov 03 '19 at 19:33
  • Could you expand on what specific features you want, then? And pls don't use txt spk. – jonrsharpe Nov 03 '19 at 19:35
  • 1
    @jonrsharpe Just because two languages have a keyword of the same name doesn't mean they have the same semantics. One really should be more careful with their gold badge privileges.. Voted to reopen. – Voo Nov 03 '19 at 19:51
  • That said to answer the question there's no syntactic sugar for this as far as I know, although you could use metaprogramming to achieve something along those lines. But honestly the sole reason to use sealed in Scala doesn't exist in Python (no pattern matching or static compiler warnings) from what I can see. – Voo Nov 03 '19 at 19:54

0 Answers0