Class Dependancy Injection

Steven Bethard steven.bethard at gmail.com
Fri Apr 13 12:49:21 EDT 2007


Robert Rawlins - Think Blue wrote:
> For instance, in my application I have a configuration bean which 
> contains all the applications configuration information. Now in one of 
> other classes I need access to those configuration settings. What I 
> would have done in my ColdFusion/JAVA type applications is create an 
> instance of the configuration bean, and then pass that in as an 
> argument to the constructor for my other class, then have the other 
> class set that as a ‘self’ variable. Then from within my class I can 
> access the configuration details like self.config.getName() and it 
> would return the name of the application.
>
> How is this best handled in python, can I still inject dependencies as 
> a constructor argument like that? If so then is there anything in 
> particular I need to watch out for that may cause me trouble?

I would tend to create a config module, rather define a singleton object 
that gets passed to every constructor. My configuration loader code 
would look something like::

     import config
     for name, value in get_config_values():
         setattr(config, name, value)

And my code that used the configuration settings would look like::

     import config
     ...
     foo(config.bar, config.baz)
     ...

I don't like the idea of adding another argument to every constructor 
for application-global configuration information. If it's really 
application-global, then use Python's built-in application-global 
objects: modules.

STeVe



More information about the Python-list mailing list