[Python-ideas] PEP 505: None-aware operators
Steven D'Aprano
steve at pearwood.info
Fri Jul 20 13:16:37 EDT 2018
On Thu, Jul 19, 2018 at 08:57:50PM -0400, Michael Selik wrote:
> Try/except also looks decent.
>
> try:
> x = foo['bar'][0]
> except TypeError:
> x = 'default'
Consider the case that foo['bar'] is supposed to return either a
collection (something that can be indexed) or None. But due to a bug, it
returns a float 1.234. Now the try...except will *wrongly* catch the
exception from 1.234[0] and return the default.
The problem here is that the try...except block is NOT equivalent to the
None-aware pattern:
obj = foo['bar'] # avoid time-of-check-to-time-of-use bugs
if obj is None:
x = 'default'
else:
x = obj[0]
except in the special case that we can guarantee that foo['bar'] can
only ever return a collection or None and will never, ever be buggy.
--
Steve
More information about the Python-ideas
mailing list