Need help with Python scoping rules

Dave Angel davea at ieee.org
Tue Aug 25 21:26:12 EDT 2009


Stephen Fairchild wrote:
> You are trying to run code in a class that does not exist yet. 
>
>
> def Demo():
>     def fact(n):
>         if n < 2:
>             return 1
>         else:
>             return n * fact(n - 1)
>     return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar":
> fact(5)})
> Demo = Demo()
>
> d = Demo()
> print d._classvar    # prints 120
> print d.fact(7)      # prints 5040
> print Demo           # prints <class '__main__.Demo'>
>
>   
In all these messages, something I haven't seen pointed out is that 
fact() has no self argument.  Seems to me that makes it a staticmethod, 
so it should be declared that way.  But you can't call a static method 
from the class scope, since the class hasn't been completed yet.  That's 
the part I consider a problem, not all the rest.  I've seen the same 
problem in Forth, where 'smudge' is used to prevent a definition from 
accidentally calling itself.  But I don't recall whether that was in the 
standard, or just vendor's helpful additions.

Anyway, my first choice is to move the static method out of the class.  
Second choice workaround follows, moving the initialization of the class 
variable to after the class, when it can properly use the class name.:

class Demo(object):
    @staticmethod
    def fact(n):
        if n < 2:
            return 1
        else:
            return n * Demo.fact(n - 1)

Demo._classvar = Demo.fact(5)

print Demo._classvar
xx = Demo()
print xx.fact(6)

DaveA



More information about the Python-list mailing list