Assign concrete class to variable

119 Views Asked by At

I have a situation where I want to choose which implementation of an ABC I want to use based on some condition:

class Base(abc.ABC):
    @abc.abstractmethod
    def func(self) -> str:
        raise NotImplementedError

class Foo(Base):
    def func(self) -> str:
        return 'foo'

class Bar(Base):
    def func(self) -> str:
        return 'bar'

def call_func(use_foo: bool) -> str:
    cls: type[Base] = Foo if use_foo else Bar
    return cls().func()

This runs just fine but mypy 1.9.0 complains

Can only assign concrete classes to a variable of type "type[Base]"

0

There are 0 best solutions below