

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Closures
incomplete
2: Closure Review
incomplete
3: Closure Practice
incomplete
4: Closure Practice
incomplete
This lesson's interactive features are locked, please to keep using them
Remember, a closure is a function that retains the state of its environment. That makes it useful for tracking data as it changes over time, but it can come at the cost of understandability.
When not to use the nonlocal keyword: when the variable is mutable – such as a list, dictionary, or set – and you're modifying its contents rather than reassigning the variable. You only need nonlocal if you're reassigning a variable (which you must do to update immutable values like strings and integers).
Let's try a closure without nonlocal.
Doc2Doc needs a function to manage a growing collection of documents. Complete the new_collection function. It accepts:
initial_docs: a list of stringsThe new_collection function should:
Each time you call the returned function, it should add to the same list (the closure keeps track of the list's state).
from collections.abc import Callable
my_collection: Callable[[str], list[str]] = new_collection(["doc1", "doc2", "doc3"])
print(my_collection("doc4"))
# ['doc1', 'doc2', 'doc3', 'doc4']
print(my_collection("doc5"))
# ['doc1', 'doc2', 'doc3', 'doc4', 'doc5']