Python Memory Management and Tips Transcripts
Chapter: Memory and functions
Lecture: Concept: Closure state
0:00 Let's round out this chapter on functions by looking at closures and closure state.
0:04 So we saw that we could almost created a little object,
0:07 a little class that has some behavior and has some data by using closures.
0:12 So our "create_counter" function here,
0:14 take some arguments to get things started.
0:16 It's going to create a variable called "current",
0:19 and it's going to capture that using "nonlocal".
0:23 It's also going to capture "step"
0:25 by the way, we just don't have to say nonlocal for it.
0:28 So this counter implementation that gets returned will have a permanent reference to current and a
0:34 permanent reference to step. This is like creating a class that has one function,
0:39 which is whatever this does here,
0:41 do the step, and then two fields, current and step.
0:45 And when we create one, here
0:46 this one, we're starting a 10 and incriminating by 7, so we're calling it "by_7s".
0:50 When we call this function, first time it used it's initial variables that it's held onto,
0:56 but then the next time, it's remembering
0:57 Its state. It's holding current and step and putting them together, and again, and again, and
1:03 again. So when you create a closure like this, just keep in mind that you're
1:07 changing the life cycle of current and step.