How to eval a file

Björn Lindberg d95-bli at nada.kth.se
Sun Feb 23 15:30:31 EST 2003


bokr at oz.net (Bengt Richter) writes:

> UIAM, the reason it doesn't work is that at the time the code is
> generated for the C.m method, the compiler can't tell that
> 'collection' will later be a local variable created by execfile, so
> the reference defaults to global, and code is generated to access
> the global, which doesn't exist and doesn't get created, hence the
> NameError exception.

<snip thorough explanation>

Thank you. Now I understand what was going on. My understanding of
execfile() was right, but I didn't think of when the
compiler/interpretor decides which variables are local or global.

I was thinking of execfile() roughly as if inserting all the lines
from the exec:d file at the point of the execfile(). As this example
shows, that is not in all cases right.

> Yup, lots of options. There are also utility modules for dealing
> with config files, and the possibility of importing the file as a
> module, as others have mentioned.

Yes, I am using the shlex module now for parsing my configuration. It
seems to be an extremely useful little module for this purpose.


Björn




More information about the Python-list mailing list