Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does typing.cast do in Python?

import typing
type(typing.cast(int, '11'))

still returns <class 'str'> instead of int. Then, what does typing.cast do here?

like image 757
Craig Avatar asked Jul 21 '18 15:07

Craig


People also ask

How is casting used in python?

Type casting is a method used to change the variables/ values declared in a certain data type into a different data type to match the operation required to be performed by the code snippet. In python, this feature can be accomplished by using constructor functions like int(), string(), float(), etc.

Is type casting bad in python?

Definitely not. I'm sure there are people who would call your current approach more Pythonic and prefer that over this. In other words, no, there is nothing wrong with what you're doing. Very interesting answer for me.


1 Answers

From the documentation (emphasis mine):

Cast a value to a type.

This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).

The "casting" only takes place in the type-checking system, not at runtime.

like image 67
Zev Chonoles Avatar answered Oct 22 '22 03:10

Zev Chonoles