如何使用依赖注入将对象注入模块?

时间:2014-06-25 06:57:00

标签: python dependency-injection module

这是我的情景。我有一个包含几个模块的包。它们全部从settings.py导入。但是,某些变量取决于用户输入。

...
# some CONSTANTS
...
PROJECT_DIR = Path(os.path.abspath(__file__)).parent.ancestor(1)
SCRIPT_DIR = PROJECT_DIR.child('scripts')
data_input = DATA_ROOT.child('input')
input_root = data_input.child(options.root_input) # the options object holds some user input

# then use input_root to get an instance of class Countries
from countries import Countries
country_object = Countries(input_root)

有几个模块需要country_object。因此从settings导入它们将是最干净的解决方案。

所以我正在阅读dependency injection,我认为这是在这里派上用场的东西。但是我发现很难包装它,所以如何使用依赖注入将选项对象注入模块?

1 个答案:

答案 0 :(得分:1)

说到模式,有两种理念,让你的问题适合模式,使模式适合你的问题。我遵循后者。所以这将是我对dependency injection模式的适应问题:

class UserCountry(object):
     def __init__(self):be populated by user data
         self.Country = None

     def set_input_root(self, input_root):
         self.input_root = input_root # <-- this is a list/dict etc that I assume will 

     def __call__(self):
         if self.Country:
             return self.Country
         else:
             # Select country
             self.Country = Country
             return self.Country
settings.py中的

 user_country = UserCountries()

定义input_root时:

settings.user_country.set_input_root(input_root) 

在其他模块中:

 settings.user_country() # gives you the Country object
相关问题