In python, define a type, then cast to that type

In support of some legacy code, I have to read a text file and parse it for operators like x=102

and file=foo.dat

, which can be used to overwrite the default values. Note that the second does not exist file='foo.dat'

; these are not python instructions, but they are close.

Now I can get the type

default object, so I know what x

must be int and file

must be str. So, I need a way to cast the right side to this type. I would like to do this programmatically, so that I can name one simple default setting function. In particular, I would rather not iterate over all the built-in types. Is it possible?

+3


source to share


2 answers


It's actually quite simple:

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

      



Now value

is an int equal to 102.

0


source


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

      



+5


source







All Articles