type annotation for return type of method where that depends on an attribute of the class

Question:

Say I have:

class A: pass
class B: pass

class Foo:

  factory: Type = A

   def make(self) -> ?:
       return self.factory()


class Bar(Foo):

   factory: Type = B

What type annotation do I use on make to indicate that the type returned is that of the factory attribute?

Asked By: Chris Withers

||

Answers:

Use generics.

from typing import TypeVar, Generic, Type

T = TypeVar('T')


class A:
    pass


class B:
    pass


class GenericFooerBarrer(Generic[T]):
    factory: Type[T]

    def make(self) -> T:
        return self.factory()


class Foo(GenericFooerBarrer[A]):
    factory: Type[A] = A


class Bar(GenericFooerBarrer[B]):
    factory: Type[B] = B


To match exactly as you wanted you would of want a default type for generic such that Foo is generic with default.
Generic default is only planned for python 3.12, so you’ll have to wait just a bit.

Answered By: Shu ba
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.