Problem with exec
Antoon Pardon
apardon at forel.vub.ac.be
Mon Dec 19 03:05:38 EST 2005
Op 2005-12-16, Peter Otten schreef <__peter__ at web.de>:
> Antoon Pardon wrote:
>
>> 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
Maybe bound methods will provide a solution, but it won't be so simple
as your suggestion. PLY uses introspection to get at the names of
productions functions. Something like:
def p_assignment(p):
'''assignment : NAME EQUALS list SEMICOL'''
print p[1], p[3]
setattr(Config , p[1] , p[3])
...
yacc.yacc() # This will somehow look into this module and collect
# all functions starting with p_ and together with
# the productions in the doc strings produce a parser.
...
yacc.parse(s) # This wil parse s and in the parse proces call
# p_assignment each time a "assignment" production
# is encountered.
Now when I put the p_ functions in a class the yacc.yacc call no longer
finds them. There may be a solution for this, but it is not in the
documentation, so I'll have to dive into the source.
--
Antoon Pardon
More information about the Python-list
mailing list