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``:
142142
143143.. code-block :: python
144144
145- def create_adders ():
145+ def create_multipliers ():
146+ multipliers = []
147+
146148 for i in range (5 ):
147- def adder (x ):
149+ def multiplier (x ):
148150 return i * x
149- yield adder
151+ multipliers.append(multiplier)
152+
153+ return multipliers
150154
151155 What You Should Do Instead
152156~~~~~~~~~~~~~~~~~~~~~~~~~~
153157
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
155159afformentioned behavior concerning evaluating default arguments to functions
156160(see :ref: `default_args `), you can create a closure that binds immediately to
157161its arguments by using a default arg like so:
158162
159163.. code-block :: python
160164
161- def create_adders ():
165+ def create_multipliers ():
162166 return [lambda x , i = i : i * x for i in range (5 )]
163167
164168 When the Gotcha Isn't a Gotcha
165169~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
166170
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
168172situations. Looping to create unique functions is unfortunately a case where
169173they can cause hiccups.
You can’t perform that action at this time.
0 commit comments