Re: Type hint question
Albert-Jan Roskam <[email protected]> Thu, 26 Sep 2024 21:10:53 +0200
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <DB9PR10MB66891D2BEE36AB522CD18EE0836A2@DB9PR10MB6689.EURPRD10.PROD.OUTLOOK.COM> |
On Sep 26, 2024 20:10, Mats Wichmann <[email protected]> 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)"? _______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor