Problem with exec

Antoon Pardon apardon at forel.vub.ac.be
Fri Dec 16 08:48:01 EST 2005


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?

-- 
Antoon Pardon



More information about the Python-list mailing list