-
Notifications
You must be signed in to change notification settings - Fork 288
typing.cast() is ignored
#1885
-
Hello,
I was trying to use typing.cast to force the type of a variable, but I can't get mypy to accept the new type and it still reports the typing error.
For instance:
import typing a = 1 typing.cast(str, a) a += "foo"
Currently fails with:
$ mypy test.py test.py:5: error: Unsupported operand types for + ("int" and "str") [operator] Found 1 error in 1 file (checked 1 source file)
... which is, in theory, correct, but I was under the assumption that typing.cast would silence mypy in this case?
I'm using mypy 1.13.0 with Python 3.12 (it has the same behavior with 3.13) ; I don't have any specific mypy settings configured here.
Beta Was this translation helpful? Give feedback.
All reactions
Hi! This is expected. cast only changes the type of an expression. It doesn't change the type of variables or otherwise propagate typing assumptions to parts of the program outside of the expression it's used on.
For example, valid (albeit dubious) uses of cast might look like
a = typing.cast(str, 1) a += "foo" # or a = 1 a += typing.cast(int, "foo")
Could you elaborate a bit on what you're trying to achieve? There might be a different typing construct better suited for the task than typing.cast.
Replies: 1 comment 1 reply
-
Hi! This is expected. cast only changes the type of an expression. It doesn't change the type of variables or otherwise propagate typing assumptions to parts of the program outside of the expression it's used on.
For example, valid (albeit dubious) uses of cast might look like
a = typing.cast(str, 1) a += "foo" # or a = 1 a += typing.cast(int, "foo")
Could you elaborate a bit on what you're trying to achieve? There might be a different typing construct better suited for the task than typing.cast.
Beta Was this translation helpful? Give feedback.
All reactions
-
Oh no, I'm stupid 🤦
I was indeed missing keeping the result of typing.cast around 🤦
Thanks for pointing this out, this is actually super useful 😅
Could you elaborate a bit on what you're trying to achieve?
I'm using an external library that has type annotations ... but incorrectly defined. I was trying to force the correct types until the library fixes its type annotations and ships a new version.
Beta Was this translation helpful? Give feedback.