File tree Expand file tree Collapse file tree 1 file changed +10
-6
lines changed Expand file tree Collapse file tree 1 file changed +10
-6
lines changed Original file line number Diff line number Diff line change @@ -142,28 +142,32 @@ fact the same exact behavior is exhibited by just using an ordinary ``def``:
142
142
143
143
.. code-block :: python
144
144
145
- def create_adders ():
145
+ def create_multipliers ():
146
+ multipliers = []
147
+
146
148
for i in range (5 ):
147
- def adder (x ):
149
+ def multiplier (x ):
148
150
return i * x
149
- yield adder
151
+ multipliers.append(multiplier)
152
+
153
+ return multipliers
150
154
151
155
What You Should Do Instead
152
156
~~~~~~~~~~~~~~~~~~~~~~~~~~
153
157
154
- Well. Here the general solution is arguably a bit of a hack. Due to Python's
158
+ The most general solution is arguably a bit of a hack. Due to Python's
155
159
afformentioned behavior concerning evaluating default arguments to functions
156
160
(see :ref: `default_args `), you can create a closure that binds immediately to
157
161
its arguments by using a default arg like so:
158
162
159
163
.. code-block :: python
160
164
161
- def create_adders ():
165
+ def create_multipliers ():
162
166
return [lambda x , i = i : i * x for i in range (5 )]
163
167
164
168
When the Gotcha Isn't a Gotcha
165
169
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166
170
167
- When you want your closures to behave this way. Late binding is good in lots of
171
+ Sometimes you want your closures to behave this way. Late binding is good in lots of
168
172
situations. Looping to create unique functions is unfortunately a case where
169
173
they can cause hiccups.
You can’t perform that action at this time.
0 commit comments