Question on nested scope

Wolfgang Grafen wolfgang.grafen at marconi.com
Fri Jul 13 12:28:51 EDT 2001


exec executes your statement within the global and local namespace as
far I remember. 

#exec (<stmnt>,<globals>, <locals>)

do the same with:

b=10
def f1(p):
  exec(p,{'b':b})
  print a
  print b

def f2(p):
  exec(p,{},{'b':b})
  print a
  print b

>>> f1(a)
b=b+11
10

>>> f2(a)
b=b+11
10

gra.

XiaoQin Xia wrote:
> 
> In Python 2.1:
> 
> >>> b=10
> >>> a="b=b+11"
> >>> def f(p):
>         exec p
>         print a
>         print b
> 
> 
> >>> f(a)
> b=b+11
> 21
> >>> b
> 10
> >>>
> 
> When exec "b=b+11", python can find the second b (10), why it generate
> another b?
> 
> Cheers,
> Xiao-Qin Xia



More information about the Python-list mailing list