How to eval a file

Alex Martelli aleax at
Sat Feb 22 18:42:51 CET 2003

Björn Lindberg wrote:

> I'm writing a program with a "configuration file" if you will, that
> looks something like this:
> --------------------------------
> collection = '''Abba %sdabba'''
> topic = '''Gucko %s'''
> --------------------------------
> I have trouble getting this information into Python. I was hoping I
> could read this file as a string and then eval() it, to get the

eval is a built-in function that evaluates expressions.

Assignments are NOT expressions in Python, but statements.

The exec statement, and the execfile built-in function,
execute statements.

More often than not exec is not a good idea, PARTICULARLY
when you don't execute things in SPECIFIED dictionaries.

> variables collection & topic set to the respective strings in the
> local context. Ie, in a class method:

The example you give doesn't look like a class method (the new
special concept introduced in Python 2.2: the first argument is
normally named cls) nor a normal instance method (where the
first argument is normally named self):

>     def read_file(name):

Having to guess at what you mean, I'll guess you mean a normal
instance method and the signature is actually:

    def read_file(self, name):

>         f = open(name, 'r')
>         string =
>         eval(string)
>         self.collection = collection
>         self.topic = topic
>         ...
>         f.close()

Simplest way to achieve what you want might be:

    def read_file(self, name):
        f = open(name, 'r')
        execfile(f, self.__dict__)

Note that you can't be sure WHICH attributes of self will
be affected by this -- it all depends on what's coded in
the file you execute.  But if you've initialized all the
interesting fields, and perhaps even included a __slots__
to raise an error when one tries to assign other fields,
then this approach might almost be acceptable (if you
trust the file you execute not to be coded with malicious
intent to cause damage, and only want to ward against
normal, accidental mistakes -- else, life's harder).


More information about the Python-list mailing list