[Tutor] How to type annotate complex dictionary containing lambdas?

boB Stepp robertvstepp at gmail.com
Sun Nov 17 14:12:48 EST 2019


On Sun, Nov 17, 2019 at 2:52 AM Alan Gauld via Tutor <tutor at python.org> wrote:
>
> On 17/11/2019 05:32, boB Stepp wrote:
> > My best effort so far to type annotate the dictionary below is to use
> > "Any" for the dictionary values.  Is there a better substitute for
> > "Any" that would more precisely type annotate these dictionary values?
>
> To be honest I wouldn't even be trying I'd be more concerned with
> getting rid of such a messy dict and replacing it with a class.
>
> Type hints are no substitute for clean code.

Chastisement taken, accepted and fully merited!

As I was staring at this program last night I was trying to recreate
in memory its history of "development" (Ha!).  Originally it was an
extremely short program with no comments, no docstrings, no input
validation.  It was just a quick and dirty throw-away program to
accept a start date, goal date to finish reading a book, and returned
how many pages to read each day to attain the goal.  But it proved to
be a convenient program to open up at need and try out different
things I was currently reading about.  So one day I was reading about
proper code documentation, so it got docstrings in profusion and a few
comments and renaming of variables, etc.  Then I read something about
input validation so I added that.  And then I got interested in
lambdas and trying things with them that I did not know if they could
do or not, such as be tools for evaluating Boolean expressions and
some other things and so it got like this dictionary snippet shows.
That was several months ago.  And so now I am getting intrigued by
type annotations, so it was time to open up the toy program and play
around with these new critters.  And as I tried to add type
annotations I wondered what in the heck I was thinking before!  So I
had the same thought last night that you expressed and almost did not
ask my question since I knew some comments would be made,  But!  I
really was curious how such a beast would be properly type annotated.

One thing that trying to write tests has taught me:  If it is
difficult to write tests for whatever, then something probably needs
to be refactored/done better.  As you might guess, I did not write any
tests for this program.  And apparently type annotations teach a
similar sort of wisdom:  If it is hard to figure out how to annotate a
given block of code, something really, really stinks!


More information about the Tutor mailing list