Skip to content

Commit 9a8c0f2

Browse files
PEP 769: Better explanation on which exceptions are captured (#4272)
* Better explanation on which exceptions are captured * Better wording
1 parent 5fe54b0 commit 9a8c0f2

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

peps/pep-0769.rst

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ The implementation of ``attrgetter`` is quite direct: it implies using
189189

190190
try:
191191
value = getattr(obj, "name")
192-
except (TypeError, IndexError, KeyError):
192+
except (IndexError, KeyError):
193193
value = XYZ
194194

195195
Note we cannot rely on using ``getattr`` with a default value, as it would
@@ -200,35 +200,41 @@ attribute chain is specified (e.g.
200200
The implementation for ``itemgetter`` and ``getitem`` is not that
201201
easy. The more straightforward way is also simple to define and
202202
understand: attempting ``__getitem__`` and catching a possible
203-
exception (any of the three indicated in ``__getitem__`` `reference`_).
204-
This way, ``itemgetter(123, default=XYZ)(obj)`` or
205-
``getitem(obj, 123, default=XYZ)`` would be equivalent to::
203+
exception (see below). This way, ``itemgetter(123, default=XYZ)(obj)``
204+
or ``getitem(obj, 123, default=XYZ)`` would be equivalent to::
206205

207206
try:
208207
value = obj[123]
209-
except (TypeError, IndexError, KeyError):
208+
except (IndexError, KeyError):
210209
value = XYZ
211210

212211
However, for performance reasons the implementation may look more
213-
like the following, which has the same exact behaviour::
212+
like the following, which has the same exact behavior::
214213

215214
if type(obj) == dict:
216215
value = obj.get(123, XYZ)
217216
else:
218217
try:
219218
value = obj[123]
220-
except (TypeError, IndexError, KeyError):
219+
except (IndexError, KeyError):
221220
value = XYZ
222221

223222
Note how the verification is about the exact type and not using
224-
``isinstance``; this is to ensure the exact behaviour, which would be
223+
``isinstance``; this is to ensure the exact behavior, which would be
225224
impossible if the object is a user defined one that inherits ``dict``
226225
but overwrites ``get`` (similar reason to not check if the object has
227226
a ``get`` method).
228227

229228
This way, performance is better but it's just an implementation detail,
230229
so we can keep the original explanation on how it behaves.
231230

231+
Regarding the exception to be captured, even if ``__getitem__``
232+
can raise ``IndexError``, ``KeyError``, or ``TypeError`` (see its
233+
`reference`_), only the first two can happen if the container does not
234+
contain the indicated key or index, and the latter is likely to signal
235+
a bug in the code, so we're not capturing it to trigger the default
236+
behavior.
237+
232238

233239
Corner Cases
234240
------------

0 commit comments

Comments
 (0)