-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Dataclass with default factory not supported. #12
Comments
nrbnlulu
changed the title
Dataclass with default factory for dict not supported.
Dataclass with default factory not supported.
Apr 11, 2024
@nrbnlulu sig = inspect.signature(FooBase.__init__)
print(sig.parameters["bar"].default) # <factory> |
I'll try to submit a PR soon |
@nrbnlulu Should be possible with #18 import dataclasses
from dataclasses import is_dataclass
from typing import Any
import aioinject
from aioinject import Provider
from aioinject.extensions.builtin import BuiltinDependencyExtractor
from aioinject.providers import Dependency
@dataclasses.dataclass(slots=True)
class FooBase[T]:
bar: dict[T] = dataclasses.field(default_factory=dict)
def baz(self):
raise NotImplementedError()
class FooImpl(FooBase[int]):
def baz(self):
pass
class DataclassExtractor(BuiltinDependencyExtractor):
def extract_supports(self, provider: Provider[Any]) -> bool:
return super().extract_supports(provider) and is_dataclass(
provider.impl
)
def extract_dependencies(
self,
provider: Provider[Any],
context: dict[str, Any],
) -> tuple[Dependency[object], ...]:
fields_with_defaults = [
f.name
for f in dataclasses.fields(provider.impl)
if isinstance(f, dataclasses.Field)
and f.default_factory != dataclasses.MISSING
]
result = super().extract_dependencies(
provider=provider, context=context
)
return tuple(r for r in result if r.name not in fields_with_defaults)
container = aioinject.Container(extensions=[DataclassExtractor()])
container.register(aioinject.Singleton(FooImpl))
with container.sync_context() as ctx:
foo_impl = ctx.resolve(FooImpl) |
Ah this is very cool |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example
To get around this what you could do something like
I guess this can be solved by ignoring fields that has default factories.
The text was updated successfully, but these errors were encountered: