Sort of neither, but closer to the first.
y = self.axes.get('y')
if y is not None:
ax = y.ax
coord1[ax] = x0
coord2[ax] = y1 - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
get
is a best-effort function that will (by default) return None
if the key doesn't exist. This approach means you only ever need to do one key lookup.
One of the reasons to prefer this method is that it can be faster than exceptions, depending on your data. To demonstrate,
#!/usr/bin/env python3
from contextlib import suppress
from sys import version
from timeit import timeit
def exception_method(axes, coord):
try:
ax = axes['y']
except KeyError:
pass
else:
coord[ax] = 0
def suppress_method(axes, coord):
with suppress(KeyError):
ax = axes['y']
coord[ax] = 0
def get_method(axes, coord):
ax = axes.get('y')
if ax is not None:
coord[ax] = 0
methods = ((suppress_method, 'contextlib.suppress'),
(exception_method, 'exception swallowing'),
(get_method, 'dict.get'))
def trial(method_index, is_present):
coord = {}
axes = {'y': 0} if is_present else {}
method, desc = methods[method_index]
def run():
method(axes, coord)
REPS = 200000
t = timeit(run, number=REPS)/REPS * 1e6
print(f'Method: {desc:20}, '
f'Key pre-exists: {str(is_present):5}, '
f'Avg time (us): {t:.2f}')
def main():
print(version)
for method in range(3):
for present in (False, True):
trial(method, present)
if __name__ == '__main__':
main()
The output is:
3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
Method: contextlib.suppress , Key pre-exists: False, Avg time (us): 8.86
Method: contextlib.suppress , Key pre-exists: True , Avg time (us): 7.71
Method: exception swallowing, Key pre-exists: False, Avg time (us): 3.70
Method: exception swallowing, Key pre-exists: True , Avg time (us): 2.93
Method: dict.get , Key pre-exists: False, Avg time (us): 2.90
Method: dict.get , Key pre-exists: True , Avg time (us): 3.00
If you can guarantee that in most cases the key will pre-exist, then the exception-swallowing method is marginally fastest. Otherwise, get
is fastest.