Fix Python – Why aren’t python nested functions called closures?


Asked By – Srikar Appalaraju

I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called “nested functions” instead of “closures”?

Are nested functions not closures because they are not used by the external world?

UPDATE: I was reading about closures and it got me thinking about this concept with respect to Python. I searched and found the article mentioned by someone in a comment below, but I couldn’t completely understand the explanation in that article, so that is why I am asking this question.

Now we will see solution for issue: Why aren’t python nested functions called closures?


A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution.

def make_printer(msg):
    def printer():
    return printer

printer = make_printer('Foo!')

When make_printer is called, a new frame is put on the stack with the compiled code for the printer function as a constant and the value of msg as a local. It then creates and returns the function. Because the function printer references the msg variable, it is kept alive after the make_printer function has returned.

So, if your nested functions don’t

  1. access variables that are local to enclosing scopes,
  2. do so when they are executed outside of that scope,

then they are not closures.

Here’s an example of a nested function which is not a closure.

def make_printer(msg):
    def printer(msg=msg):
    return printer

printer = make_printer("Foo!")
printer()  #Output: Foo!

Here, we are binding the value to the default value of a parameter. This occurs when the function printer is created and so no reference to the value of msg external to printer needs to be maintained after make_printer returns. msg is just a normal local variable of the function printer in this context.

This question is answered By – aaronasterling

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0