[Tutor] Readability: To use certain Python features or not?

boB Stepp robertvstepp at gmail.com
Sun Jun 27 17:41:17 EDT 2021


Questions inspired by an example from "Practical Programming, 3rd ed."
by Gries, Campbell and Montojo.

p. 221 example.  Compare:

[...]
bird_to_observations = {}
for line in observations_file:
    bird = line.strip()
    if bird in bird_to_observations:
        bird_to_observations[bird] = bird_to_obserations[bird] + 1
    else:
        bird_to_observations[bird] = 1
[...]

to

[...]
bird_to_observations = {}
for line in observations_file:
    bird = line.strip()
    bird_to_observations[bird] = bird_to_observations.get(bird, 0) + 1
[...]

The authors comment:  "Using the get method makes the program shorter,
but some programmers find it harder to understand at a glance..."

To my mind *if* the reader is fully familiar with Python the second
example is both shorter and more expressive.  For the most
maintainable code which of these is better?  What assumptions about
our code's future audience should we hold to best help our future
readers of our code?

Note that I am asking a different set of questions from another common
topic:  When to use Python constructs like list comprehensions,
lambdas, etc., which can greatly shorten LOC, but easily become a sea
of letters when one makes them too complex.

TIA!
boB Stepp


More information about the Tutor mailing list