Re: Type hint question
Mats Wichmann <[email protected]> Thu, 26 Sep 2024 12:10:58 -0600
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <[email protected]> |
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...
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor