Import and execfile()

Mike Meyer mwm-keyword-python.b4bdba at mired.org
Fri Jan 11 17:24:11 EST 2008


On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis <george.sakkis at gmail.com> wrote:

> I maintain a few configuration files in Python syntax (mainly nested
> dicts of ints and strings) and use execfile() to read them back to
> Python. This has been working great; it combines the convenience of
> pickle with the readability of Python. So far each configuration is
> contained in a single standalone file; different configurations are
> completely separate files.

You know, I've been there before. It's kinda neat, but not something
you really want to put in the hands of most users.

You can make the syntax cleaner by using classes to hold the values
instead of nested dicts, etc. That way you don't have to quote the
names of the values:

class Foo:
  bar = 1
  baz = 2

The really slick part was that if the config classes line up with the
implementation classes, you can create an instance of the config class
for the implementation object, and it can then change those values to
change it's behavior without changing the defaults other instances
see.

> Now I'd like to factor out the commonalities of the different
> configurations in a master config and specify only the necessary
> modifications and additions in each concrete config file. I tried the
> simplest thing that could possibly work:

With classes you factor out the commonality by factoring it into a
base class that the others inherit from.

> ======================
> # some_config.py
> 
> # master_config.py is in the same directory as some_config.py
> from master_config import *
> 
> # override non-default options
> foo['bar']['baz] = 1
> ...
> 
> ======================
> # trying to set the configuration:
> CFG = {}
> execfile('path/to/some_config.py', CFG)
> 
> Traceback (most recent call last):
> ...
> ImportError: No module named master_config
> 
> 
> I understand why this fails but I'm not sure how to tell execfile() to
> set the path accordingly. Any ideas ?

Manipulate sys.path yourself?

   <mike

-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.



More information about the Python-list mailing list