Skip to content
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

Open
nrbnlulu opened this issue Apr 11, 2024 · 2 comments
Open

Dataclass with default factory not supported. #12

nrbnlulu opened this issue Apr 11, 2024 · 2 comments

Comments

@nrbnlulu
Copy link
Contributor

nrbnlulu commented Apr 11, 2024

example

import dataclasses

import aioinject


@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


container = aioinject.Container()
container.register(aioinject.Singleton(FooImpl))

with container.sync_context() as ctx:
	foo_impl = ctx.resolve(FooImpl)

To get around this what you could do something like

import dataclasses
from typing import TYPE_CHECKING

import aioinject


@dataclasses.dataclass(slots=True)
class FooBase[T]:
	if TYPE_CHECKING:
		bar: dict[T] = dataclasses.field(default_factory=dict)
	else:
		bar: dict = dataclasses.field(default_factory=dict)

	def baz(self):
		raise NotImplementedError()


class FooImpl(FooBase[int]):
	def baz(self):
		pass


container = aioinject.Container()
container.register(
	aioinject.Transient(dict),
    aioinject.Singleton(FooImpl)
    )

with container.sync_context() as ctx:
	foo_impl = ctx.resolve(FooImpl)

I guess this can be solved by ignoring fields that has default factories.

@nrbnlulu nrbnlulu changed the title Dataclass with default factory for dict not supported. Dataclass with default factory not supported. Apr 11, 2024
@ThirVondukr
Copy link
Owner

@nrbnlulu
I think it's possible to just ignore parameters that have default arguments but honestly I'm not sure if they should be ignored or if container should try to resolve them 🤔

sig = inspect.signature(FooBase.__init__)
print(sig.parameters["bar"].default)  # <factory>

@nrbnlulu
Copy link
Contributor Author

I'll try to submit a PR soon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants