Style: global configuration data

Peter Hansen peter at engcorp.com
Sun Nov 12 10:31:55 EST 2000


Boudewijn Rempt wrote:
> 
> I have been wondering for some time about the best way to offer
> configuration data and other global resources to all modules and classes
> in my application, other than creating a config object and passing that
> on with every constructor.  What's the received Pythonic wisdom on this?
> 
> I'd prefer to just have one instance of my config class, or my repository
> class or whatever, so if I were working in Java I'd create a singleton, but
> that somehow doesn't seem right for Python to me.

I'm not the best one to answer this (no doubt Alex is :-), but I
wouldn't say that singletons are un-Pythonic.  In fact, the effect of
the "import" statement is singleton-ish...  The first time it is
executed as "import spam", the module spam is searched for, found,
loaded, etc. in memory.  Subsequent calls, even from other modules, do
not reload spam but merely go and create a new reference in the calling
code's namespace to the already-loaded module spam (effectively "spam =
sys.modules['spam']").

For configuration data, it would probably not be improper to use exactly
the same mechanism: just have an "import myconfig" in each module that
needs access to your "global" data, and let that data be defined as
straight code in the module myconfig.py... or have myconfig.py load the
config data from an appropriate place when it executes.

-- 
Peter Hansen



More information about the Python-list mailing list