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

How To resolve class dependencies registered by key #35

Open
jbcpollak opened this issue Apr 15, 2020 · 3 comments
Open

How To resolve class dependencies registered by key #35

jbcpollak opened this issue Apr 15, 2020 · 3 comments
Labels
enhancement New feature or request

Comments

@jbcpollak
Copy link
Contributor

lets say I have something like this:

class Dependency:
     pass

class ConsumerOfA:
    def __init__(self, dep: Dependency):
        self.dep = dep

container.register('depA', Dependency('a'))
container.register('depB', Dependency('b'))
container.register(ConsumerOfA)

cOA = container.resolve(ConsumerOfA)

How do I ensure that ConsumerOfA gets depA vs depB? Is there a way to add an annotation on init to make sure the right one is injected?

@bobthemighty
Copy link
Owner

This also sounds like a sensible feature. I'll take a look at this one, too :)

@bobthemighty bobthemighty added the enhancement New feature or request label Jun 5, 2020
@strmwalker
Copy link

This could be achieved with string annotations on __init__ args:

class Dependency:
     pass

class ConsumerOfA:
    def __init__(self, dep: 'depA'):
        self.dep = dep

container.register('depA', Dependency('a'))
container.register('depB', Dependency('b'))
container.register(ConsumerOfA)

cOA = container.resolve(ConsumerOfA)

Drawback of this approach is that you introducing DI to your client code, and this breaks static analysis tools like mypy.

@strmwalker
Copy link

Just figured out best way to solve this problem. You can use typing.NewType to create aliases:


from punq import Container


class Dependency:
    def __init__(self, value):
        self.value = value


DependencyA = NewType('DependencyA', Dependency)
DependencyB = NewType('DependencyB', Dependency)


class ConsumerOfA:
    def __init__(self, dep: DependencyA):
        self.dep = dep


class ConsumerOfB:
    def __init__(self, dep: DependencyB):
        self.dep = dep


def main():
    container = Container()
    container.register(DependencyA, instance=Dependency('a'))
    container.register(DependencyB, instance=Dependency('b'))
    container.register(ConsumerOfA)
    container.register(ConsumerOfB)
    coa: ConsumerOfA = container.resolve(ConsumerOfA)
    cob: ConsumerOfB = container.resolve(ConsumerOfB)
    print(coa.dep.value)
    print(cob.dep.value)


if __name__ == '__main__':
    main()

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

No branches or pull requests

3 participants