1

As I understand it, a client (the core program) needs to have a common type to allow a plugin, another object, etc. to be passed successfully to a client. I saw this answer on SO here,

What is dependency injection?

In Java, passing by constructor using an prescript Interface makes sense. From the SO question mentioned,

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

As I understand it, MyClass is a type defined by an Interface. myObject implements that, is required to in fact, thus allowing me to pass myObject to the constructor.

So how does Dependency Injection work in duck typing language? Python has no Interfaces. Is Python's DI implementation the same as Java or other statically typed languages, or a "workaround" type DI for scripting languages?

Community
  • 1
  • 1
johnny
  • 19,272
  • 52
  • 157
  • 259

1 Answers1

2

The need for an interface is just a detail of Java. It's the thing that lets you define a function that can accept an instance of any of several otherwise-unrelated types.

Since every Python function can accept an instance of any type, there is no need for anything comparable.

Of course, if you pass in an object that doesn't have the required capability then you'll get an exception at some point. Python has what is called "implicit interfaces" -- the interface required by the function is whatever operations it performs on the object in the expectation of them working.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • Thanks. How do I *guarantee* I get the correct type passed to my core class? In Java, if I require an Interface implementation, I can make the plugin designer using my Interface. How can I do that in Python? – johnny Mar 27 '14 at 19:05
  • 1
    Document your code, include explicit specs in the documentation, expect the specs to be followed. When all else fails, catch the exception. – wwii Mar 27 '14 at 19:32
  • 1
    @johnny: first, bear in mind that implementing an interface just means the object has the right method signatures. It doesn't guarantee the object behaves correctly, you're always reliant on someone implementing the spec. Python says, "type isn't everything, in fact it's so little that we aren't going to bother with guaranteeing it at every opportunity like Java does". That said, in Python you can use `type()` or `instanceof()` to check type if you really need to, and you can use ABCs to explicitly define interfaces if you want to. – Steve Jessop Mar 27 '14 at 19:42
  • @SteveJessop Yes, but doesn't the Interface make the plugin create have certain methods and properties? It looks like for the languages without Interfaces then a naming convention is used, at least that's what I saw in PHP. It doesn't matter as long as the patter works. For whatever reason I felt like Interface was more foolproof. – johnny Mar 28 '14 at 15:08