Recursive function defined within function => NameError

Thomas A. Bryan tbryan at python.net
Thu Feb 17 12:30:37 CET 2000


Michael Ströder wrote:
> 
> HI!
> 
> I have a problem with a locally-defined recursive function within a
> function. Example:
> 
> ---------------
> def func1():
> 
>   def fak(n):
>     if n>1:
>       return n*fak(n-1)
>     else:
>       return n
> 
>   print fak(6)
> 
> func1()
> ---------------
> 
> But this code snippet does not work. It produces the traceback:
> 
> Traceback (innermost last):
>   File "test/rec-func.py", line 15, in ?
>     func1()
>   File "test/rec-func.py", line 9, in func1
>     print fak(6)
>   File "test/rec-func.py", line 5, in fak
>     return n*fak(n-1)
> NameError: fak
> 
> Can anybody clarify the issue here? I looked in the Language
> Reference and found the hint
> 
> ---------------
> Programmer's note: a ``def'' form executed inside a function
> definition defines a local function that can be returned or passed
> around. Because of Python's two-scope philosophy, a local function
> defined in this way does not have access to the local variables of
> the function that contains its definition;
> ---------------
> 
> I applied the standard trick showed there to my example and the
> following code works:
> 
> ---------------
> def func1():
> 
>   def fak(n,fak):
>     if n>1:
>       return n*fak(n-1,fak)
>     else:
>       return n
> 
>   print fak(6,fak)
> 
> func1()
> ---------------
> 
> Any better solution?

Better in what sense?  This works, but I'm not sure whether it's 
useful.  

class Recursive:
  """A base class for recursive function objects"""
  def _func(self,n):
    """subclasses should override this method"""
    pass  
  def __call__(self, n):
    """This method calls the instance's function."""
    return self._func(n)

class Fak(Recursive):
  """A recursive implementation of factorial."""
  def _func(self,n):
    if n>1:
      return n * self._func(n-1)
    else:
      return n

>>> f = Fak()
>>> f(6)
720


RuntimeError:-Maximum-recursion-depth-exceeded-ly yours
---Tom



More information about the Python-list mailing list