In python, detect type, then cast to that type

Go To StackoverFlow.com

3

In support of some legacy code, I have to read a text file and parse it for statements like x=102 and file=foo.dat that might be used to overwrite default values. Note that the second one there is not file='foo.dat'; these aren't python statements, but they're close.

Now, I can get the type of the default object, so I know that x should be an int and file should be a str. So, I need a way to cast the right-hand side to that type. I'd like to do this programmatically, so that I can call a single, simple default-setting function. In particular, I'd prefer to not have to loop over all the built-in types. Is it possible?

2012-04-04 22:56
by NoName
What do you mean by "I can get the type of the default object" - David Heffernan 2012-04-04 22:59


0

It's actually pretty easy:

textfromfile = '102'
defaultobject = 101
value = (type(defaultobject))(textfromfile)

Now, value is an int equal to 102.

2012-04-04 23:02
by Mike
No need for the extra braces: type(defaultobject)(textfromfile)orlp 2012-04-04 23:03
True. I just prefer this syntax - Mike 2012-04-04 23:10


5

# Get the type object from the default value
value_type = type(defaults[fieldname])

# Instantiate an object of that type, using the string from the input
new_value = value_type(override_value)
2012-04-04 23:00
by Amber
Ads