Type inference in a IoC container class, return type of the resolve method

51 Views Asked by At

I have a simple IoC class implementation:

Abs = TypeVar('Abs', str, Type)

class MyContainer:
    _bindings: dict = {}
    _aliases: dict = {}

    def resolve(abstract: Abs):
        # something along these lines...
        abstract = (
            self._aliases[abstract]
            if isinstance(abstract, str)
            else abstract
        )
        factory = self._bindings.get(abstract)
        return factory()

    def bind(abstract: Type, factory: typing.Callable, alias: str = None) -> None:
        # something along these lines...
        self._bindings[abstract] = factory
        if alias:
            self._aliases[alias] = abstract

And I use it like so:

ioc = MyContainer()

def some_factory():
    return SomeConcrete()

ioc.bind(SomeAbstract, some_factory, alias="some")

# Both work nice!
ioc.resolve(SomeAbstract)
ioc.resolve("some")

Now I'm wondering if there's a way to make my editor be able to tell what would the return type of a call to ioc.resolve be regardless of what type of abstract I use (Type, or str)?

0

There are 0 best solutions below