python-injector / injector

Python dependency injection framework, inspired by Guice
BSD 3-Clause "New" or "Revised" License
1.3k stars 81 forks source link

Providing different instances of the same type in the same module #237

Closed chriscoindeskindices closed 1 year ago

chriscoindeskindices commented 1 year ago

I need to do something like this where I need two different instances of the same type

@provider
def get_instance1() -> Foo:
  return Foo(1)

@provider
def get_instance2() -> Foo:
  return Foo(2)

@provider
def get_bar(f1:Foo, f2:Foo) -> Bar:
  return Bar(f1, f2)

But obviously that has some issues. I suppose I could do something like this:

@provider
def get_foo() -> Foo:
  return Foo()

@provider
def get_bar(f1:Foo, f2:Foo) -> Bar:
  f1.prop = 1
  f2.prop = 2
  return Bar(f1, f2)

This should work because get_foo is not a singleton, but it's not always easy or possible with some of my classes in their current way they are written.

davidparsson commented 1 year ago

Creating new types with NewType can be used to achieve this. There's an example in this issue: https://github.com/python-injector/injector/issues/148