pythoncastingmypy

Python: typing.cast vs built in casting


Is there any difference between the typing.cast function and the built-in cast function?

x = 123
y = str(x)
from typing import cast
x = 123
y = cast(str, x)

I expected that mypy might not like the first case and would prefer the typing.cast but this was not the case.


Solution

  • str(x) returns a new str object, independent of the original int. It's only an example of "casting" in a very loose sense (and one I don't think is useful, at least in the context of Python code).

    cast(str, x) simply returns x, but tells a type checker to pretend that the return value has type str, no matter what type x may actually have.

    Because Python variables have no type (type is an attribute of a value), there's no need for casting in the sense that languages like C use it (where you can change how the contents of a variable are viewed based on the type you cast the variable to).