modern-python / that-depends

DI-framework, inspired by python-dependency-injector, but without wiring. Python 3.12 is supported
https://that-depends.readthedocs.io/
MIT License
133 stars 10 forks source link

Application Settings example typing error #59

Closed roger-collins-self closed 1 month ago

roger-collins-self commented 1 month ago

Given the example in the docs:

from that_depends import BaseContainer, providers

class DIContainer(BaseContainer):
    settings: Settings = providers.Singleton(Settings).cast
    some_factory = providers.Factory(SomeFactory, service_name=settings.service_name)

and injecting the settings elsewhere:

@inject
def get_value(settings: Settings = Provide[Container.settings]) -> str:
    return settings.my_value

Results in a mypy error:

error: Invalid index type "Settings" for "type[Provide]"; expected type "AbstractProvider[Never]"  [index]

The code executes correctly, but just doesn't pass type checking.

Is there a right way to do this?

lesnik512 commented 1 month ago

@roger-collins-self Hi, you can change as following

from that_depends import BaseContainer, providers

class DIContainer(BaseContainer):
    settings = providers.Singleton(Settings)
    settings_casted: Settings = settings.cast
    some_factory = providers.Factory(SomeFactory, service_name=settings_casted.service_name)

And than this will work without mypy error:

@inject
def get_value(settings: Settings = Provide[Container.settings]) -> str:
    return settings.my_value
lesnik512 commented 1 month ago

I will update this in docs as well