Need help with Python scoping rules

7stud bbxx789_05ss at yahoo.com
Tue Aug 25 20:36:46 CEST 2009


On Aug 25, 12:11 pm, John Posner <jjpos... at optimum.net> wrote:
> 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.
>
> Buthttp://docs.python.org/tutorial/classes.htmlsays, 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


I guess a counter example would be something like this:

y = "hello"

class Demo(object):
    y = "goodbye"

    def __init__(self):
        self.x = 10
        print y

Demo()

--output:--
hello


>
> 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.
>

python ignores the names inside a function when it creates the
function.  This "program" will not produce an error:


def f():
    print x

python parses the file and creates the function object and assigns the
function object to the variable f.  It's not until you execute the
function that python will raise an error.  The same thing happens with
the recursive function.





More information about the Python-list mailing list