[Tutor] Type hint question
Albert-Jan Roskam
sjeik_appie at hotmail.com
Thu Sep 26 12:57:15 EDT 2024
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:
try:
return int(value.strip(" "))
except (TypeError, AttributeError, ValueError):
return value
n = try_int(" 1")
I get this message:
main.py:7: error: Incompatible return value type (got "int", expected "T")
[return-value]
main.py:7: error: "T" has no attribute "strip" [attr-defined]
Found 2 errors in 1 file (checked 1 source file)
Thanks!
Albert-Jan
More information about the Tutor
mailing list