File tree 1 file changed +11
-7
lines changed
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``:
143
143
144
144
.. code-block :: python
145
145
146
- def create_adders ():
146
+ def create_multipliers ():
147
+ multipliers = []
148
+
147
149
for i in range (5 ):
148
- def adder (x ):
150
+ def multiplier (x ):
149
151
return i * x
150
- yield adder
152
+ multipliers.append(multiplier)
153
+
154
+ return multipliers
151
155
152
156
What You Should Do Instead
153
157
~~~~~~~~~~~~~~~~~~~~~~~~~~
154
158
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
157
161
(see :ref: `default_args `), you can create a closure that binds immediately to
158
162
its arguments by using a default arg like so:
159
163
160
164
.. code-block :: python
161
165
162
- def create_adders ():
166
+ def create_multipliers ():
163
167
return [lambda x , i = i : i * x for i in range (5 )]
164
168
165
169
When the Gotcha Isn't a Gotcha
166
170
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167
171
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
169
173
situations. Looping to create unique functions is unfortunately a case where
170
174
they can cause hiccups.
You can’t perform that action at this time.
0 commit comments