Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 08b8eec

Browse files
author
Kenneth Reitz
committed
Merge pull request realpython#265 from simon-weber/gotcha_fixes
Fix naming and confusing example in gotchas
2 parents 34f026c + aa25ef5 commit 08b8eec

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

docs/writing/gotchas.rst

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff 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
158162
its 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
169173
situations. Looping to create unique functions is unfortunately a case where
170174
they can cause hiccups.

0 commit comments

Comments
 (0)