Need help with Python scoping rules

Ethan Furman ethan at stoneleaf.us
Wed Aug 26 15:00:02 EDT 2009


kj wrote:
> 
> 
> I have many years of programming experience, and a few languages,
> under my belt, but still Python scoping rules remain mysterious to
> me.  (In fact, Python's scoping behavior is the main reason I gave
> up several earlier attempts to learn Python.)
> 
> Here's a toy example illustrating what I mean.  It's a simplification
> of a real-life coding situation, in which I need to initialize a
> "private" class variable by using a recursive helper function.
> 
> class Demo(object):
>     def fact(n):
>         if n < 2:
>             return 1
>         else:
>             return n * fact(n - 1)
> 
>     _classvar = fact(5)

As has been pretty thoroughly discussed, the issue here is not 
recursion, but name lookup.

Going back through the archives I found Arnaud's post with this decorator:

def bindfunc(f):
     def boundf(*args, **kwargs):
         return f(boundf, *args, **kwargs)
     return boundf

If you use it on your fact function like so...

class Demo(object):
     @bindfunc
     def fact(recurse, n)	# recurse can be any name you like
         if n < 2:
             return 1
         else:
             return n * recurse(n-1)
     _classvar = fact(5)
     del fact			# no longer needed, and won't work
				# once class is created

This should do as you want.

As a side note, if you're going to bother asking questions on this list, 
you really should try to understand the answers.  I won't gripe at you 
too much, though, 'cause I learned a lot from the many responses given 
due to your refusal to do so.  ;-)

~Ethan~



More information about the Python-list mailing list