[Tutor] Type hint question

Mats Wichmann mats at wichmann.us
Thu Sep 26 14:10:58 EDT 2024


On 9/26/24 10:57, Albert-Jan Roskam wrote:
>     Hi,
>     I just started using type hints and mypy so this is probably a basic
>     question. Why doesn't like mypy the code below? Also, I noticed that mypy
>     seems to favour LBYL (if isinstance) to EAFP (try-except), in the sense
>     that doesn't understand the latter well. Is this true? I'm still learning
>     to use mypy, but sometimes it feels a lot like "pleasing mypy". Then
>     again, it has already helped me find some errors.

>     from typing import TypeVar
>     T = TypeVar("T")
>     def try_int(value: T) -> T:

so that says *value* can be any type, but the return value must be the 
same type

>         try:
>             return int(value.strip(" "))

and here, if *value* was a string, you perform a string op on it and 
won't get an exception, then turn that into an int for returning - which 
clearly isn't the same type as was passed in.  Ergo, some complaint 
should be expected.

>         except (TypeError, AttributeError, ValueError):
>             return value
> 

The TypeVar will probably be more useful if it applies some contraint...


More information about the Tutor mailing list