[Tutor] Type hint question
Albert-Jan Roskam
sjeik_appie at hotmail.com
Thu Sep 26 15:05:49 EDT 2024
On Sep 26, 2024 19:50, Oscar Benjamin via Tutor <tutor at python.org> wrote:
On Thu, 26 Sept 2024 at 18:12, Albert-Jan Roskam
<sjeik_appie at hotmail.com> 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.
More information about the Tutor
mailing list