[Tutor] Variable scope for class?

Dave Kuhlman dkuhlman at rexx.com
Fri Aug 31 00:53:47 CEST 2007


On Thu, Aug 30, 2007 at 06:02:12PM -0400, Orest Kozyar wrote:
> I'm trying to follow the example listed in the wiki at
> http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject regarding the
> use of a metaclass.  
> 
> What I don't understand is how the metaclass (EntitySingleton) has access to
> the variable ctx which is instantinated outside the scope of the class
> definition.  Could anyone point me in the right direction please?

Alan's book has a chapter on this (chapter 16 "Namespaces", in
"Learn to Program using Python").  And, "Learning Python", by Mark Lutz
also covers it.

You will need to pay attention to the LEGB rule, which basically
says that Python searches for a name in namespaces in the following
order:

1. Local
2. Enclosing (specifically enclosing functions if this is a nested
   function)
3. Global
4. Built-ins

So, in your specific example, Python looks:

1. In the Local namespace, but can't find ctx.
2. The enclosing namespace, but there is none, since this
   function/method is not nested in another one.
3. The Global namespace, where it finds "ctx" and quits.

One thing to keep in mind, is that Python looks for names
(variables) in the namespaces where a class or method or function
is defined, *not* in the namespaces where those objects are used or
called.

So far so good.  But, here is the one I do not understand.

    G1 = 111
    class A(object):
        G1 = 222
        def show(self):
            print G1

    def test():
        a = A()
        a.show()

    test()

But, when I run this I see "111", not "222".

Why is that?  "G1 = 222" is in the enclosing scope, right?

Well, I guess that is wrong.  Apparently in Python, a class does
not create an enclosing scope.

Actually, the particular edition of Alan's book that I have is old
enough so that it does not discuss the Enclosing namespace, which
came later to Python.  The enclosing namespace not make a
difference in your example, but does in mine.

Dave



-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list