Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 619
jofreem Avatar asked Dec 16 '25 13:12

jofreem


1 Answers

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).

like image 185
chepner Avatar answered Dec 19 '25 01:12

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!