File tree Expand file tree Collapse file tree 1 file changed +11
-7
lines changed
Expand file tree Collapse file tree 1 file changed +11
-7
lines changed Original file line number Diff line number Diff line change @@ -143,28 +143,32 @@ fact the same exact behavior is exhibited by just using an ordinary ``def``:
143143
144144.. code-block :: python
145145
146- def create_adders ():
146+ def create_multipliers ():
147+ multipliers = []
148+
147149 for i in range (5 ):
148- def adder (x ):
150+ def multiplier (x ):
149151 return i * x
150- yield adder
152+ multipliers.append(multiplier)
153+
154+ return multipliers
151155
152156 What You Should Do Instead
153157~~~~~~~~~~~~~~~~~~~~~~~~~~
154158
155- Well. Here the general solution is arguably a bit of a hack. Due to Python's
156- aforementioned behavior concerning evaluating default arguments to functions
159+ The most general solution is arguably a bit of a hack. Due to Python's
160+ afformentioned behavior concerning evaluating default arguments to functions
157161(see :ref: `default_args `), you can create a closure that binds immediately to
158162its arguments by using a default arg like so:
159163
160164.. code-block :: python
161165
162- def create_adders ():
166+ def create_multipliers ():
163167 return [lambda x , i = i : i * x for i in range (5 )]
164168
165169 When the Gotcha Isn't a Gotcha
166170~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167171
168- When you want your closures to behave this way. Late binding is good in lots of
172+ Sometimes you want your closures to behave this way. Late binding is good in lots of
169173situations. Looping to create unique functions is unfortunately a case where
170174they can cause hiccups.
You can’t perform that action at this time.
0 commit comments