Recently, I was trying to store and read information from files in Python, and came across a slight problem: I wanted to read type information from text files. Type casting from string to int or to float is quite efficient, but type casting from string to type seems to be another problem. Naturally, I tried something like this:
var_type = type('int')
However, type
isn't used as a cast but as a mechanism to find the type of the variable, which is actually str
here.
I found a way to do it with:
var_type = eval('int')
But I generally try to avoid functions/statements like eval
or exec
where I can. So my question is the following: Is there another pythonic (and more specific) way to cast a string to a type?