[Tutor] Readability: To use certain Python features or not?
alan.gauld at yahoo.co.uk
alan.gauld at yahoo.co.uk
Sun Jun 27 17:49:28 EDT 2021
Personally I think the second is more reliable and maintainable so prefer
it. If a reader is so new to python they don't know about get() then they
need to look it up and learn. But OTOH a default dict might be better
still!
There is a difference between writing clever code that is unreadable and
using standard language or library features that might be less well known.
One is easy to look up, the other is just downright hard work and
therefore fragile.
On 27 Jun 2021 22:41, boB Stepp <robertvstepp at gmail.com> wrote:
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
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list