0

I'm having a very difficult time trying to figure out how to implement Dependency Injection with Python. All the examples I've seen are fairly complex or not self explanatory. Java versions look very simple.

public SomeClass (MyClass myObject) {
    this.myObject = myObject;
}

I asked a related question here, but it really didn't help me with the actual code itself.

Can someone please show me a simple, very simple, way to implement Dependency Injection in Python. I am using it to build a program that can accept plugins, better testing ability, and so on. Thanks.

Community
  • 1
  • 1
johnny
  • 19,272
  • 52
  • 157
  • 259
  • 2
    As Steve told you: just pass in the object. `class Foo():`, `def __init__(self, some_object): self.some_object = some_object`. Then use `self.some_object` in your code. Done. – Martijn Pieters Mar 28 '14 at 17:58
  • I hope I did not come across as the previous question wasn't helpful. It was, and I'm thankful. I just needed to see very simple code. – johnny Mar 28 '14 at 17:59

1 Answers1

1

Following the example on Wikipedia, you can implement it similar to below. Given that Python is a dynamically typed language, you can pass any object into the constructor.

Keep in mind that you want to pay close attention to when and how you handle exceptions (e.g. if an incorrect service is passed in, the service is missing methods, attributes, etc).

If you want to enforce an interface on either client or service, define an abstract base class.

class Service():
    def __str__(self):
        return "Look ma, no static typing!"

class Client():
    def __init__(self, service):
        self.service = service

    def greet():
        return "Hello" + str(self.service)
mdadm
  • 1,333
  • 1
  • 12
  • 9