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).
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 convertx
to a string. Python doesn't actually have casting in the sense statically typed languages do. – Deputation