Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Reviewing Closures

00:00 You now know what a closure is, and you’ve seen two brief examples. In the next section of this course, you look at more use cases from within Python. But before we do that, let’s briefly summarize the key points that you have learned in this first section.

00:15 You’ll recall that in an earlier lesson before I showed you what closures are, I gave you a somewhat formal definition of a closure. A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.

00:32 Lexical scope is a fancy way of saying the scope where the variable or the object is defined. So this is telling us that a closure, which is the inner function, retains access to variables defined in a scope outside of it, the enclosing scope, the outer function, even when the call to the outer function is completed.

00:54 You’ve seen in the examples that the outer function, such as print_with_memory() or print_with_counter(), you call them once the function they return, you assign it to some variables such as print_, but the outer function, whether it’s print_with_memory() or print_with_counter(), no longer exists beyond that point.

01:14 However, the inner function, which you assigned to print_ still maintains access to either the list contained record of arguments as in the first example, or the variable counter, which is the integer containing number of times the function is called.

01:31 We can state this in a different way, so the closure, which you define as an inner function, has a reference to objects created in the enclosing scope, and therefore it can still use those objects and modify them.

01:44 You’ve also seen how you can use the nonlocal keyword in the inner function when you need to modify an immutable object defined in the enclosing scope.

01:53 This is not an issue when you have a mutable object such as list_record. Because mutable objects can be changed, it’s immutable objects that cannot be changed, and therefore the only way to change the value is by creating a new object and assigning it to the same variable name, such as counter = counter + 1.

02:12 In those instances, you need to define the variable as nonlocal. And to finish off this lesson and this section, here’s how you can think of closures.

02:21 It’s a way to allow function calls to communicate with previous and future function calls through the data within the closure.

02:30 Great. You’re now ready to look at some examples. We’ll have a look at these in section two.

Become a Member to join the conversation.