Closures remember
Not met yet
A function defined inside another can use the outer function's variables, and keeps hold of them after the outer one has finished. That inner function is a closure. Each call to the outer function makes fresh variables, so make_offer(50) and make_offer(10) remember different numbers. A closure looks a variable up when it runs, not when it was made, which catches people out in loops. To change an outer variable, not just read it, mark it nonlocal.
Try it
main.pyOutput
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks an inner function can no longer use the outer function's variables once the outer function has returned.
- Thinks every function made by the same factory shares one copy of its variables, so the latest call wins.
- Thinks a function made in a loop remembers the loop variable's value at the moment it was made, rather than looking it up when called.