Get int-type from 'int' string

后端 未结 4 836
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')
    
    >>> foo = getattr(__builtins__, 'int')
    >>> isinstance(foo, type)
    True
    

提交回复
热议问题