Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection to modules

Consider a module, e.g. some_module, that various modules use in the same interpreter process. This module would have a single context. In order for some_module methods to work, it must receive a dependency injection of a class instance.

What would be a pythonic and elegant way to inject the dependency to the module?

like image 935
Jonathan Livni Avatar asked Jun 24 '11 13:06

Jonathan Livni


2 Answers

Use a module global.

import some_module
some_module.classinstance = MyClass()

some_module can have code to set up a default instance if one is not received, or just set classinstance to None and check to make sure it's set when the methods are invoked.

like image 109
kindall Avatar answered Sep 21 '22 15:09

kindall


IMHo opinion full fledged Dependency Injection with all jargon is better suited to statically typed languages like Java, in python you can accomplish that very easily e.g here is a bare bone injection

class DefaultLogger(object):
   def log(self, line):
      print line

_features = {
   'logger': DefaultLogger
   }

def set_feature(name, feature):
   _features[name] = feature

def get_feature(name):
   return _features[name]()

class Whatever(object):

   def dosomething(self):
      feature = get_feature('logger')

      for i in range(5):
         feature.log("task %s"%i)

if __name__ == "__main__":
   class MyLogger(object):
      def log(sef, line):
         print "Cool",line

   set_feature('logger', MyLogger)

   Whatever().dosomething()

output:

Cool task 0
Cool task 1
Cool task 2
Cool task 3
Cool task 4

If you think something is missing we can add that easily, its python.

like image 34
Anurag Uniyal Avatar answered Sep 23 '22 15:09

Anurag Uniyal