Problem with exec
Larry Bates
larry.bates at websafe.com
Fri Dec 16 09:22:48 EST 2005
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()
>
>
> When I execute this I get the following error:
>
> Traceback (most recent call last):
> File "mod1.py", line 13, in ?
> foo()
> File "mod1.py", line 10, in foo
> exec "assign()" in dct
> File "<string>", line 1, in ?
> File "mod1.py", line 5, in assign
> setattr(config, 'Start' , [13, 26, 29, 34])
> NameError: global name 'config' is not defined
>
> Now I don't understand this. In the documentation I read the following:
>
> If only the first expression after in is specified, it should be a
> dictionary, which will be used for both the global and the local
> variables.
>
> I provided a dictionary to be used for the global variables and it
> contains a 'config' entry, so why doesn't this work?
>
Not entirely sure why you want to do what you have outlined
here but this works:
class Cfg:
pass
#config = Cfg()
def assign(config):
setattr(config, 'Start' , [13, 26, 29, 34])
def foo():
config = Cfg()
assign(config)
print config.Start
foo()
You should probably post what you are trying to do. Maybe we
can make a suggestion about the best approach.
-Larry Bates
More information about the Python-list
mailing list