The "right" way to use config files

Ben Finney ben+python at benfinney.id.au
Sat Aug 9 08:17:25 EDT 2014


Fabien <fabien.maussion at gmail.com> writes:

> So I had the idea to define a super-object which parses the config
> file and input data and is given as a single parameter to the
> processing functions, and the functions take the information they need
> from it.

That's not a bad idea, you could do that without embarrassment.

A better technique, though, is to make use of modules as namespaces.
Have one module of your application be responsible for the configuration
of the application::

    # app/config.py

    import configparser

    parser = configparser.ConfigParser()
    parser.read("app.conf")

and import that module everywhere else that needs it::

    # app/wibble.py

    from . import config

    def frobnicate():
        do_something_with(config.foo)

By using an imported module, the functions don't need to be
parameterised by application-wide configuration; they can simply access
the module from the global scope and thereby get access to that module's
attributes.

> To get to the point: is it good practice to give all elements of a
> program access to the configfile and if yes, how is it done
> "properly"?

There should be an encapsulation of the responsibility for parsing and
organising the configuration options, and the rest of the application
should access it only via that encapsulation.

Putting that encapsuation in a module is an appropriately Pythonic
technique.

-- 
 \          “Now Maggie, I’ll be watching you too, in case God is busy |
  `\       creating tornadoes or not existing.” —Homer, _The Simpsons_ |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list