Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

typing.cast() is ignored #1885

Answered by brianschubert
multani asked this question in Q&A
Discussion options

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.

You must be logged in to vote

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

Comment options

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.

You must be logged in to vote
1 reply
Comment options

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.

Answer selected by multani
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /