Python: typing.cast vs built in casting
Asked Answered
R

1

9

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.

Roberson answered 4/1, 2023 at 19:55 Comment(1)
cast doesn't do anything. It's a no-op, purely for the type-checker: github.com/python/cpython/blob/…. str on the other hand actually tries to convert x to a string. Python doesn't actually have casting in the sense statically typed languages do.Deputation
B
11

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

Branham answered 4/1, 2023 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.