Import and execfile()

Mike Meyer mwm-keyword-python.b4bdba at
Sat Jan 12 20:59:39 CET 2008

On Fri, 11 Jan 2008 20:55:07 -0800 (PST) George Sakkis <george.sakkis at> wrote:
> On Jan 11, 5:24 pm, Mike Meyer <mwm-keyword-python.b4b... at>
> wrote:
> > On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis <george.sak... at> 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 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
> Actually I am using the dict() constructor instead of literals so it's
> as clean as with classes; IMO for nested options it's cleaner than
> nested classes:

Yup, that does that. Wasn't available last time I did this, so...
> > > 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?
> That's what Mitko suggested too, and indeed it works:
> However this doesn't look very clean to me. Also it's not thread-safe;

I don't know that there is a clean solutions. As for not being
thread-safe, I'd suggest that you should have all your configuration
information loaded *before* you start any threads. This makes shutting
down in case you decide there's something wrong in it easier, and in
some cases may prevent inadvertently doing things that shouldn't
oughta be done. In the case where you config files are parsed by the
python interpreter, this goes double because a busted config file
could lead to exceptions, leaving your application in an unknown

Mike Meyer <mwm at>
Independent Network/Unix/Perforce consultant, email for more information.

More information about the Python-list mailing list