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

Mark Lawrence breamoreboy at gmail.com
Sun Jun 27 18:42:59 EDT 2021


On 27/06/2021 22:49, Alan G via Tutor wrote:
>     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!

Perhaps a counter? 
https://docs.python.org/3/library/collections.html#collections.Counter

>     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
-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list