@@ -189,7 +189,7 @@ The implementation of ``attrgetter`` is quite direct: it implies using
189
189
190
190
try:
191
191
value = getattr(obj, "name")
192
- except (TypeError, IndexError, KeyError):
192
+ except (IndexError, KeyError):
193
193
value = XYZ
194
194
195
195
Note we cannot rely on using ``getattr `` with a default value, as it would
@@ -200,35 +200,41 @@ attribute chain is specified (e.g.
200
200
The implementation for ``itemgetter `` and ``getitem `` is not that
201
201
easy. The more straightforward way is also simple to define and
202
202
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::
206
205
207
206
try:
208
207
value = obj[123]
209
- except (TypeError, IndexError, KeyError):
208
+ except (IndexError, KeyError):
210
209
value = XYZ
211
210
212
211
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 ::
214
213
215
214
if type(obj) == dict:
216
215
value = obj.get(123, XYZ)
217
216
else:
218
217
try:
219
218
value = obj[123]
220
- except (TypeError, IndexError, KeyError):
219
+ except (IndexError, KeyError):
221
220
value = XYZ
222
221
223
222
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
225
224
impossible if the object is a user defined one that inherits ``dict ``
226
225
but overwrites ``get `` (similar reason to not check if the object has
227
226
a ``get `` method).
228
227
229
228
This way, performance is better but it's just an implementation detail,
230
229
so we can keep the original explanation on how it behaves.
231
230
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
+
232
238
233
239
Corner Cases
234
240
------------
0 commit comments