Type hint question
Albert-Jan Roskam <[email protected]> Thu, 26 Sep 2024 18:57:15 +0200
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <DB9PR10MB6689FF89505FA660FBA1AA0F836A2@DB9PR10MB6689.EURPRD10.PROD.OUTLOOK.COM> |
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
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor