Recursive function defined within function => NameError

Martin von Loewis loewis at
Thu Feb 17 13:46:49 CET 2000

Michael Ströder <michael.stroeder at> writes:

> Can anybody clarify the issue here? I looked in the Language
> Reference and found the hint

You found the right place in the documentation. A function can only
access its own local and the module's global symbols; as a result,
looking for 'fak' gives a NameError.

> Any better solution?

For what problem? Computing the factorial in a local function? Sure:

def func1():

    def fak(n):
        from operator import mul
        if n<=1: return n
        return reduce(mul,range(1,n))

    print fak(6)


For defining support functions? Make them global, and prefix them with
an underscore:

def _fak(n):
  if n>1:
    return n*_fak(n-1)
    return n

def func1():
  print _fak(6)


This will prevent anybody importing your module with 'from foo import
*' to accidently overwrite a name; it also makes sufficiently clear
that this function is not intended for general use.


More information about the Python-list mailing list