So, I need to cast a value to a given type:
if 'int' == type_name:
value = int(value)
elif 'str' == type_name:
value = str(value)
...
Is there a way to do that generically? E.g.:
type_instance = get_type_instance(type_name)
value = type_instance(value)
I'm using Python 2.7, but would be interested in a Python 3.X solution as well.
Update:
Here's the solution I'm using:
class Token:
def __init__(self, type_name, value):
self.type = type_name
self.value = __builtins__[type_name](value) # not safe
This is just a toy parser. Don't use in production!