[Tutor] Readability: To use certain Python features or not?
boB Stepp
robertvstepp at gmail.com
Mon Jun 28 18:31:39 EDT 2021
On Mon, Jun 28, 2021 at 3:29 AM Peter Otten <__peter__ at web.de> wrote:
> > So if I am understanding your answer to the more general questions,
> > you believe that even using less well-known Python standard features
> > is desirable if it simplifies the code presentation and is more
> > expressive of intent?
>
> You didn't ask me, but I always try to use the "best fit" that I know of
> rather than the "best known fit" -- at least when that best fit is
> provided by the stdlib.
>
> In this case that would be
>
> birds = (line.strip() for line in observations_file)
> bird_to_observations = collections.Counter(birds)
>
> If that isn't self-explanatory wrap it in a function with proper
> documentation
No, that is rather self-explanatory!
> def count_birds(birds):
> """Count birds by species.
> >>> count_birds(
> ... ["norwegian blue", "norwegian blue", "unladen swallow"])
> Counter({'norwegian blue': 2, 'unladen swallow': 1})
> """
> return collections.Counter(birds)
>
> This has the advantage that the function could contain any
> implementation that satisfies the doctest. As a consequence you can
> start with something that barely works and refine it as you learn more,
> without affecting the rest of the script.
One of the problems I encounter with being actively engaged with a
book is that I am immersed in the authors' perspective and focused on
the points they are trying to make. This leads to a certain tunnel
vision on my part. As this section of the book was explaining
dictionaries and their use, that is what I was focused on as well.
Alan's suggestion fit in with that current focus. OTOH, if some one
had given me this programming problem free of a textbook's context, I
think the Counter would have occurred to me. Your solution, Peter,
definitely wins the "no prize"! (That's an old reference to Marvel
Comics)
But the main intent of my questions was not the actual problem, but
whether one should use the best standard Python tool for the job even
if it is not well-known by a substantial number of programmers or to
cater to their possible lack of knowledge. I think you and Alan have
settled that point in my mind now -- choose the best, most expressive
tool Python provides. The future maintainer can look it up if they
are lacking knowledge. And Mark in his post I think would agree from
his seconding of a Counter solution.
As always, thanks!
boB Stepp
More information about the Tutor
mailing list