开发者

Get int-type from 'int' string

In Python, given the string'int', how can I get the type in开发者_JAVA技巧t? 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


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


Try with an eval():

>>>eval('int')
<type 'int'>

But be sure of what you give to eval(); it could be dangerous.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜