Need help with Python scoping rules

John Posner jjposner at optimum.net
Tue Aug 25 14:11:32 EDT 2009


Diez said:
>
> Classes are not scopes. 
>
> So the above doesn't work because name resolution inside functions/methods
> looks for local variables first, then for the *global* scope. There is no
> class-scope-lookup.

But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A 
First Look at Classes":

When a class definition is entered, a new namespace is created,
and used as the local scope — thus, all assignments to local variables
go into this new namespace. In particular, function definitions bind
the name of the new function here.


The following example confirms this:

class Spam(object):
clsvar_1 = 555
clsvar_2 = clsvar_1 + 222

def __init__(self):
print "Spam instance initialized"

sp = Spam()
print sp.clsvar_1, sp.clsvar_2

output:
Spam instance initialized
555 777


Does the OP (kj) have a legitimate gripe, though? I confess that I know 
nothing about Python's implementation -- I'm strictly a user. So it's 
just a suspicion of mine that
something special enables a recursive function definition to refer to 
the function's own name before the definition has been completed. It 
works at the module-namespace (i.e. global) level, and Diez's "toy 
example" shows that it works at function-namespace level:

    class Demo(object):

        def fact(n):
            def inner(n):
                if n < 2:
                    return 1
                else:
                    return n * inner(n - 1)
            return inner(n)

        _classvar = fact(5)


So why can't it work at the class-namespace level, too?

(BTW, Diez, your toy example is another demonstration that there *is* a 
class-scope-lookup: the "def" statement binds the name "fact" in the 
class scope, and the assignment statement looks up the name "fact" in 
that scope.)

-John




More information about the Python-list mailing list