python-dependency-injector
python-dependency-injector copied to clipboard
How to configure a dataclass with default values?
Suppose one have a dataclass with default values specified inside it. What is the best way to use this defaults in providers.Configuration? And another question: how do you pass config values to dataclass factory without specifying all fields explicitly?
At the moment, I've came up with this usage, but I'm not very happy with foo factory declaration, because I have to update it every time I add a new field to Foo:
from dataclasses import dataclass, asdict
from dependency_injector import containers, providers
# defaults are specified in dataclass itself
@dataclass
class Foo:
bar: str = "default_value"
baz: int = 42
class Container(containers.DeclarativeContainer):
config = providers.Configuration(
default=dict(
foo=asdict(Foo()),
),
)
# this works, but it is a little bit verbose
foo = providers.Factory(
Foo,
bar=config.foo.bar,
baz=config.foo.baz,
)
# I want something like this, but it gives error
#foo = providers.Factory(
# Foo,
# **config.foo
#)