2
\$\begingroup\$

When checking a python dict for a key, which is the better way here: (I can't figure how to use dict.get() to make this cleaner)

if 'y' in self.axes:
    ax = self.axes['y'].ax
    coord1[ax] = x0
    coord2[ax] = (y1) - height[ax]
    coord3[ax] = x0 + width[ax]
    coord4[ax] = y1

or:

try:
    ax = self.axes['y'].ax
except KeyError:
    pass
else:
        coord1[ax] = x0
        coord2[ax] = (y1) - height[ax]
        coord3[ax] = x0 + width[ax]
        coord4[ax] = y1

The latter way is closer to EAFP but former seems clearer, especially for new code contributors who are scientists first & coders second.

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ I wonder if the upcoming syntax if ax := axis.get('y') is not None: coord[ax] = 0 will bring improvements. \$\endgroup\$ Dec 12, 2018 at 17:36
4
\$\begingroup\$

Both ways are valid and have their own advantages. Checking upfront using an if statement involve a bit of overheard for each usage, using EAFP involve greater overheads but only for the "wrong" case.

So if you mostly have cases where 'y' is in self.axes then EAFP is better, otherwise LBYL is fine.

But if you only are calling this pattern a handful of times, then either will do; or no, use the third approach contextlib.suppress because this except: pass is ugly:

from contextlib import suppress


with suppress(KeyError):
    ax = self.axes['y'].ax
    coord1[ax] = x0
    coord2[ax] = (y1) - height[ax]
    coord3[ax] = x0 + width[ax]
    coord4[ax] = y1
\$\endgroup\$
1
  • \$\begingroup\$ I know that it's considered Pythonic to do "logic by exception", but in every other language it's discouraged, and it creeps me out. \$\endgroup\$
    – Reinderien
    Dec 12, 2018 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.