In Python, given the string\'int\'
, how can I get the type int
? Using getattr(current_module, \'int\')
doesn\'t work.
int
isn't part of the namespace of your current module; it's part of the __builtins__
namespace. So you would run getattr
on __builtins__
.
To verify that it's a type you can just check whether it's an instance of type
, since all types are derived from it.
>>> getattr(__builtins__, 'int')
<type 'int'>
>>> foo = getattr(__builtins__, 'int')
>>> isinstance(foo, type)
True
Try with an eval()
:
>>>eval('int')
<type 'int'>
But be sure of what you give to eval()
; it could be dangerous.
With this sort of thing, if you're expecting a limited set of types, you should use a dictionary to map the names to the actual type.
type_dict = {
'int': int,
'str': str,
'list': list
}
>>> type_dict['int']('5')
5
If you don't want to use eval
, you can just store a mapping from string to type in a dict, and look it up:
>>> typemap = dict()
>>> for type in (int, float, complex): typemap[type.__name__] = type
...
>>> user_input = raw_input().strip()
int
>>> typemap.get(user_input)
<type 'int'>
>>> user_input = raw_input().strip()
monkey-butter
>>> typemap.get(user_input)
>>>