Reputation: 3078
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!
Upvotes: 6
Views: 3633
Reputation: 66003
Since you specified float64
in an earlier version of the question, I assumed you were also interested in getting numpy types. If so, the following function should solve this:
def can_typecast(type, value):
try:
tp = getattr(__builtins__, type)
except AttributeError:
try:
np = __import__('numpy')
tp = getattr(np, type)
if not isinstance(tp, type):
raise ValueError('type string is not a type')
except AttributeError:
raise ValueError('Invalid type specified')
except ImportError:
raise ValueError('Numpy not found')
try:
tp(value)
except ValueError:
return False
return True
What this does is it first looks to see if the given type name can be resolved to a built-in type. If that fails, it looks to see if the type name can be found in numpy and if it is a valid type object and if so, tries the cast operation on that.
Upvotes: 0
Reputation: 6232
If you need only __builtins__
types you can do
value = getattr(__builtins__, type_name)(value)
Upvotes: 7
Reputation:
Build a dict
TYPES = {
'int' : int,
'str' : str,
...
}
value = TYPES[type_name](value)
Upvotes: 7