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!
If you need only __builtins__
types you can do
value = getattr(__builtins__, type_name)(value)
Build a dict
TYPES = {
'int' : int,
'str' : str,
...
}
value = TYPES[type_name](value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With