Problem with exec

Fredrik Lundh fredrik at pythonware.com
Fri Dec 16 09:34:44 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.

I thought you were an expert?

Python's lexically scoped, not dynamically scoped.  Using a specific
global context for the statement "assign()" doesn't mean that code
called by that statement will suddenly get the same global context.

</F> 






More information about the Python-list mailing list