[Tutor] Type hint question

Albert-Jan Roskam sjeik_appie at hotmail.com
Thu Sep 26 15:10:53 EDT 2024


   On Sep 26, 2024 20:10, Mats Wichmann <mats at wichmann.us> wrote:

     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

   ====
   Thanks! Maybe it was fatigue but I didn't see this earlier, even though
   it's so obvious!

     >         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...

   ===
   You mean TypeVar("T", str, int) or something similar? Or "if
   isinstance(value, str)"?


More information about the Tutor mailing list