开发者

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 i开发者_运维技巧nstance.

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


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.


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.


You can use the dependencies package to achieve your goal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜