[Tutor] Type annotation errors

Mats Wichmann mats at wichmann.us
Thu Jun 4 11:32:39 EDT 2020


On 6/3/20 10:30 PM, boB Stepp wrote:
> As I continue to integrate type annotations with David Beazley's
> recently released course, "Practical Python Programming", I ran into
> another issue.  I have pared down a larger function to just what seems
> to be giving the type annotation complaint:
> 
> def parse_csv(data_rows: List, has_headers: bool = True) -> List:
>     """Parse a CSV file into a list of records."""
>     data_rows_iter = iter(data_rows)
>     if has_headers:
>         headers = next(data_rows_iter)
>     records = []
>     for row in data_rows_iter:
>         if has_headers:
>             # Make a dictionary
>             record = dict(zip(headers, row))
>         else:
>             # Otherwise make a tuple
>             record = tuple(row)
>     records.append(record)
> 
>     return records
> 
> The complaint is:  test.py|19 col 22 error| Incompatible types in
> assignment (expression has type "Tuple[Any, ...]", variable has type
> "Dict[Any, Any]")
> 
> One of the exercises is to return a list of dictionaries if a csv file
> has headers, but if not to return a list of tuples.  mypy apparently
> does not like this. 

I don't like it either :)   (I know, who am I to criticize dabeaz - even
if I did so professionally for a very short period as one of his
technical editors on Python Essential Reference 2:e way back in 2000).

Functions/methods that return different types under different calling
scenarios  are certainly possible in Python, but that doesn't mean it's
a great idea for usability.  A contrived learning example is fine; In
Real Life, I don't see why on earth you'd want this awkward setup. So
worrying too much about twisting typing so mypy is happy about this
doesn't seem terribly worthwhile... just sayin'.




More information about the Tutor mailing list