Need help with Python scoping rules

John Posner jjposner at optimum.net
Tue Aug 25 21:31:48 CEST 2009


7stud said:
> 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.
>   


Thanks for that explanation. So in the OP's example:

Class Demo(object):
    def fact(n):
        if n < 2:
            return 1
        else:
            return n * fact(n - 1)

    _classvar = fact(5)


... no failure occurs when "fact(5)" is invoked, because the lookup of 
"fact" in the local scope is a class-scope-lookup, which succeeds. The 
failure occurs on the first recursive invocation of fact() in the 
statement "return n * fact(n - 1)": the function-scope-lookup of "fact" 
fails, and then the interpreter falls back to a global-scope-lookup of 
"fact", which also fails.




More information about the Python-list mailing list