Skip to content

Commit 5da8f3e

Browse files
committed
gotchas: fix naming; remove generator in def example
1 parent 7b180cc commit 5da8f3e

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

docs/writing/gotchas.rst

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff 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
155159
afformentioned behavior concerning evaluating default arguments to functions
156160
(see :ref:`default_args`), you can create a closure that binds immediately to
157161
its 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
168172
situations. Looping to create unique functions is unfortunately a case where
169173
they can cause hiccups.

0 commit comments

Comments
 (0)