Problem with exec

Peter Otten __peter__ at web.de
Fri Dec 16 10:31:45 EST 2005


Antoon Pardon wrote:

> 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.


Maybe you could use a bound method?

class Cfg:
    def assign(self):
        setattr(self, 'Start' , [13, 26, 29, 34])

def foo():
    config = Cfg()
    namespace = dict(assign=config.assign)
    exec "assign()" in namespace
    print config.Start

Peter




More information about the Python-list mailing list