Is it possible to type-hint a strict subclass of a given type?

41 Views Asked by At

Let's say I wanted to hint that a particular field of a dataclass should be a subclass of one class, but not the type itself. For a more concrete example:

class Foo:
    ...

class Bar(Foo):
    ...

class Baz(Foo):
    ...

@dataclass
class Data:
    foo_subclass_instance: StrictSubclassOf[Foo]  # accepts an instance of Bar or Baz, but not a Foo
    foo_subclass: type[StrictSubclassOf[Foo]]  # accepts Bar or Baz, but not Foo

If the set of subclasses is small and known in advance, you can work around this with something like this:

@dataclass
class Data:
    foo_subclass_instance: Bar | Baz
    foo_subclass: type[Bar] | type[Baz]

However, this approach breaks down if you have a lot of subtypes to keep track of, potentially with some of those being in other files you can't import because doing so would create import cycles.

So is there some sort of annotation to describe StrictSubclassOf[T]?

0

There are 0 best solutions below