Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > locals() and globals()

Reply
Thread Tools

locals() and globals()

 
 
Paolo Pantaleo
Guest
Posts: n/a
 
      10-14-2006
Hi

this exaple:

def lcl():
n=1
x=locals()
x["n"]=100
print "n in lcl() is:" +str(n)
#This will say Name error
#x["new"]=1
#print new


n=1
x=globals()
x["n"]=100
print "gobal n is:" +str(n)
x["new"]=1
print "new is:" +str(new)
lcl()

produces

gobal n is:100
new is:1
n in lcl() is:1

shouldn't be n in lcl() 100 too?

why accessing the names dictionary globals() and locals() gives
different results?
This example was made using
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32

PAolo
 
Reply With Quote
 
 
 
 
Kay Schluehr
Guest
Posts: n/a
 
      10-14-2006
Paolo Pantaleo wrote:
> Hi
>
> this exaple:
>
> def lcl():
> n=1
> x=locals()
> x["n"]=100
> print "n in lcl() is:" +str(n)
> #This will say Name error
> #x["new"]=1
> #print new
>
>
> n=1
> x=globals()
> x["n"]=100
> print "gobal n is:" +str(n)
> x["new"]=1
> print "new is:" +str(new)
> lcl()
>
> produces
>
> gobal n is:100
> new is:1
> n in lcl() is:1
>
> shouldn't be n in lcl() 100 too?
>
> why accessing the names dictionary globals() and locals() gives
> different results?


Python is statically scoped. The name bindings are fixed at compile
time. Hence you can't achieve dynamic scoping by using the locals()
dictionary and add new names to the locals() which might eventually be
used as local variables in the body of the function. The function still
controls its own state and does not permit delegating state changes via
locals(). That's what objects are for.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
if and and vs if and,and titi VHDL 4 03-11-2007 05:23 AM



Advertisments