Get int-type from 'int' string

后端 未结 4 835
Happy的楠姐
Happy的楠姐 2021-01-25 08:21

In Python, given the string\'int\', how can I get the type int? Using getattr(current_module, \'int\') doesn\'t work.

相关标签:
4条回答
  • 2021-01-25 09:01

    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
    
    0 讨论(0)
  • 2021-01-25 09:03

    Try with an eval():

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

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

    0 讨论(0)
  • 2021-01-25 09:10

    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
    
    0 讨论(0)
  • 2021-01-25 09:14

    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)
    >>>
    
    0 讨论(0)
提交回复
热议问题