Re: Type hint question
Albert-Jan Roskam <[email protected]> Thu, 26 Sep 2024 21:05:49 +0200
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <DB9PR10MB6689B1CEF92CB6E050AF744D836A2@DB9PR10MB6689.EURPRD10.PROD.OUTLOOK.COM> |
On Sep 26, 2024 19:50, Oscar Benjamin via Tutor <[email protected]> wrote: On Thu, 26 Sept 2024 at 18:12, Albert-Jan Roskam <[email protected]> wrote: > > > 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) Those errors are reasonable. You have declared the parameter and return types to both be T. That means that this should return the same type as the input although note that "type" here is not exactly the same as "type" in the usual Python sense although usually it means the same thing. You are calling the function with a string and it will return an int. This is not consistent with saying that the return type is the same ==== Arrgh. Of course! How stupid of me. **** That makes perfect sense. Thank you. Personally I wouldn't use "EAFP" like this for TypeError. Catching the ValueError for a string whose value might not be valid seems reasonable but types I would check explicitly whether with a TypeChecker or isinstance() and I would only use isinstance() at the boundaries. ==== Isn't try-except cheaper if the "except" is relatively rare? Also, I thought try/except wss considered to be more pythonic... but I don't know where I read that. _______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor