Problem with exec

Antoon Pardon apardon at forel.vub.ac.be
Fri Dec 16 10:16:35 EST 2005


Op 2005-12-16, Larry Bates schreef <larry.bates at websafe.com>:
> Antoon Pardon wrote:
>> I have the following little piece of code:
>> 
>> class Cfg:pass
>> #config = Cfg()
>> 
>> def assign():
>>   setattr(config, 'Start' , [13, 26, 29, 34])
>> 
>> def foo():
>>   config = Cfg()
>>   dct = {'config':config, 'assign':assign}
>>   exec "assign()" in dct
>>   print config.Start
>> 
>> foo()

> [ ... ]
>
> You should probably post what you are trying to do.  Maybe we
> can make a suggestion about the best approach.

I'm using PLY. The assign function is a dumbded down version
of a production function that will be called during the parsing
of a config file. Each time a line of the form:

 var = val

is encounterd I do setattr(config, 'var', val)

The problem is that doing it this way means config needs to be global.
which I'm trying to avoid, in case some leftovers may cause trouble
when I read in a new configuration or should I ever have different
threads parsing files at the same time. 

The other way would be passing the 'config' variable around in the
productions, but this would complicate things.

So what I am trying to do was provide a global namespace to the call
to fool a function using a global name into using a provided local name.

-- 
Antoon Pardon



More information about the Python-list mailing list