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

Skip to content

Commit 12c3cd7

Browse files
committed
Closes #14306: clarify expensiveness of try-except and update code snippet
1 parent f2123d2 commit 12c3cd7

1 file changed

Lines changed: 5 additions & 5 deletions

File tree

Doc/faq/design.rst

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -284,8 +284,9 @@ Similar methods exist for bytes and bytearray objects.
284284
How fast are exceptions?
285285
------------------------
286286

287-
A try/except block is extremely efficient. Actually catching an exception is
288-
expensive. In versions of Python prior to 2.0 it was common to use this idiom::
287+
A try/except block is extremely efficient if no exceptions are raised. Actually
288+
catching an exception is expensive. In versions of Python prior to 2.0 it was
289+
common to use this idiom::
289290

290291
try:
291292
value = mydict[key]
@@ -296,11 +297,10 @@ expensive. In versions of Python prior to 2.0 it was common to use this idiom::
296297
This only made sense when you expected the dict to have the key almost all the
297298
time. If that wasn't the case, you coded it like this::
298299

299-
if mydict.has_key(key):
300+
if key in mydict:
300301
value = mydict[key]
301302
else:
302-
mydict[key] = getvalue(key)
303-
value = mydict[key]
303+
value = mydict[key] = getvalue(key)
304304

305305
For this specific case, you could also use ``value = dict.setdefault(key,
306306
getvalue(key))``, but only if the ``getvalue()`` call is cheap enough because it

0 commit comments

Comments
 (0)