Providers - pass config dict as kwargs to provided class
Opened this issue · 1 comments
frenzyk commented
Is there any way to pass config dict as **kwargs to my class?
There is 2 problem I try to solve:
- Too many args will lead to an additional manual labor of mapping config
- in example below
session_dbhas a default, which become useless as if not provided in config it will beNone.
from dependency_injector import containers, providers
class Client:
def __init__(
self,
api_id: int,
session_db: str | Path = "some default value",
):
self.api_id = api_id
self.session_db = session_db
class ApplicationContainer(containers.DeclarativeContainer):
config = providers.Configuration()
my_client = providers.Singleton(
Client,
config.client.api_id,
config.client.session_db,
)
container = ApplicationContainer()
container.config.from_dict(
{
"client": {
"api_id": "id",
},
},
)
my_client = container.my_client()
assert my_client.session_db == "some default value"What I want is something like
class ApplicationContainer(containers.DeclarativeContainer):
config = providers.Configuration()
my_client = providers.Singleton(
Client,
**config.client
)ZipFile commented
With current implementation it is not possible to do it exactly the way you described, but you can try this instead:
my_client = providers.Singleton(
lambda kwargs: Client(**kwargs),
kwargs=config.client,
)