rsokl / Learning_Python

Source material for Python Like You Mean it
https://www.pythonlikeyoumeanit.com/
Other
163 stars 54 forks source link

Use TypeVar instead of Any for type-hint exercise #199

Closed tbazin closed 1 year ago

tbazin commented 1 year ago

Hi!

Nice project :) Was just browsing through and I saw the solution to the assignment in Module 5 here uses explicit Any annotations where using a generic would seem more appropriate and better from a pedagogical perspective (I believe explicit Any annotations should generally be avoided). But I get that generics may be considered too advanced for introductory classes.

The solution would then be:

from typing import Any, Sequence, Tuple, TypeVar

T = TypeVar('T')

def get_first_and_last(x: Sequence[T]) -> Tuple[T, T]:
    """Returns the first and last elements of `x`. `x` is
    assumed to be non-empty
    """
    return (x[0], x[-1])
rsokl commented 1 year ago

Hi @tbazin ! Thanks for the write-up. You are certainly correct that this is the appropriate place for a TypeVar. My concern, though - as you highlighted - is that this might be a bit too complicated for the reader. I'll mull it over.