This is an old copy of the Python FAQ. The information here may be outdated.

Where do nested functions live?

Q: I defined a nested function:

def foo():
    def bar():
        return "bar"
    return "foo " + bar()

which works. Knowing how Python loves namespaces, I thought I could do, but that doesn’t work as expected.

A: The reason for this is that local functions, just like local variables, only exist in the local scope of an executing function. This is no different from ordinary local variables:

def foo():
    bar = "who am I? where do I live?"

This also means that an inner function is created every time you execute the outer function (but it’s created from prefabricated parts, so that’s not a very expensive process).

If you want something that can be called and define its attributes, you want something more complex than the default function type. Define a class that has a __call__ attribute, make an instance of that, and you’ll be able to access attributes and call it like a function.

(Based on python-list postings by Steven D’Aprano, Ben Finney, and Fredrik Lundh).


A Django site. rendered by a django application. hosted by webfaction.