Sunday, July 29, 2012

dependency injection in python

Dependency injection (DI) is a software reuse pattern, and has quite a lot of literature associated with it. Most of the videos you see on this topic start off with a small explanation of the SOLID principles. These principles are a set of guides to good object-oriented (OO) design. The 'D' in SOLID refers to dependency inversion - or dependency injection.

I found a very good video which explains the situation where we would actually go for this pattern. It is targeted to php audiences, but those who understand the basic OO principles can follow it easily.

Now python being a dynamic language the term dependency injection isn't as popular as it is in c# or java. This being because, python is a dynamic language. You assume can link to any bit of code at runtime and execute that functionality. If you have spawned up an instance of the python interpreter, you can write functions on the fly and execute them.



Python also has the notions of modules: they are mechanisms to enforce some modular approach to programming. This is also a way to accomplish reuse. You can write some functionality in them and import them into your main script or the interpreter instance, and use that functionality right away. In fact a lot of what is in the python standard library is reused this way.


Below is an example showing you how you can write your own module and import that one:



I have my own implementation of dependency injection hosted on github right now. It is inspired from spring.net library (.net library for di). But before you look at the code, and, if you are still unsure of how exactly python import statements work, you should look here.

Looking forward to interact with people on my google plus profile. Happy programming.
Post a Comment