locals() and globals()

Discussion in 'Python' started by Paolo Pantaleo, Oct 14, 2006.

  1. 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
    Paolo Pantaleo, Oct 14, 2006
    #1
    1. Advertising

  2. Paolo Pantaleo

    Kay Schluehr Guest

    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.
    Kay Schluehr, Oct 14, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Giles Brown

    Question about "exec in globals, locals"

    Giles Brown, Jul 4, 2003, in forum: Python
    Replies:
    2
    Views:
    342
    Adrien Di Mascio
    Jul 4, 2003
  2. tedsuzman
    Replies:
    2
    Views:
    7,061
    Michel Claveau, résurectionné d'outre-bombe inform
    Jul 21, 2004
  3. Ted
    Replies:
    1
    Views:
    451
    Duncan Booth
    Jul 22, 2004
  4. Olivier Sessink
    Replies:
    0
    Views:
    380
    Olivier Sessink
    Feb 24, 2005
  5. Faisal Alquaddoomi

    Globals, Locals Dictionaries + Callbacks Question

    Faisal Alquaddoomi, Dec 21, 2005, in forum: Python
    Replies:
    3
    Views:
    353
    Steve Holden
    Dec 22, 2005
Loading...

Share This Page