代码之家  ›  专栏  ›  技术社区  ›  Nas Banov

如何获取所有Python类型的列表(以编程方式)?

  •  5
  • Nas Banov  · 技术社区  · 16 年前

    a recent question ,那个 min/max() 需要对象具有可比性,这让我想知道如何找到哪些Python类型支持特定方法( __cmp__ ,或者 __lt__ -细节不重要)。

    首先,获取所有类型列表的能力似乎是关键。然后我可以简单地检查一下 hasattr(thisType, '__cmp__')

    3 回复  |  直到 9 年前
        1
  •  10
  •   tzot    16 年前
    >>> import __builtin__
    >>> builtin_types= [t
    ...  for t in __builtin__.__dict__.itervalues()
    ...  if isinstance(t, type)]
    
    >>> import pprint
    >>> pprint.pprint(sorted(builtin_types, key=repr))
    [<type 'basestring'>,
     <type 'bool'>,
     <type 'buffer'>,
     <type 'bytearray'>,
     <type 'classmethod'>,
     <type 'complex'>,
     <type 'dict'>,
     <type 'enumerate'>,
     <type 'exceptions.ArithmeticError'>,
     <type 'exceptions.AssertionError'>,
     <type 'exceptions.AttributeError'>,
     <type 'exceptions.BaseException'>,
     <type 'exceptions.BufferError'>,
     <type 'exceptions.BytesWarning'>,
     <type 'exceptions.DeprecationWarning'>,
     <type 'exceptions.EOFError'>,
     <type 'exceptions.EnvironmentError'>,
     <type 'exceptions.Exception'>,
     <type 'exceptions.FloatingPointError'>,
     <type 'exceptions.FutureWarning'>,
     <type 'exceptions.GeneratorExit'>,
     <type 'exceptions.IOError'>,
     <type 'exceptions.ImportError'>,
     <type 'exceptions.ImportWarning'>,
     <type 'exceptions.IndentationError'>,
     <type 'exceptions.IndexError'>,
     <type 'exceptions.KeyError'>,
     <type 'exceptions.KeyboardInterrupt'>,
     <type 'exceptions.LookupError'>,
     <type 'exceptions.MemoryError'>,
     <type 'exceptions.NameError'>,
     <type 'exceptions.NotImplementedError'>,
     <type 'exceptions.OSError'>,
     <type 'exceptions.OverflowError'>,
     <type 'exceptions.PendingDeprecationWarning'>,
     <type 'exceptions.ReferenceError'>,
     <type 'exceptions.RuntimeError'>,
     <type 'exceptions.RuntimeWarning'>,
     <type 'exceptions.StandardError'>,
     <type 'exceptions.StopIteration'>,
     <type 'exceptions.SyntaxError'>,
     <type 'exceptions.SyntaxWarning'>,
     <type 'exceptions.SystemError'>,
     <type 'exceptions.SystemExit'>,
     <type 'exceptions.TabError'>,
     <type 'exceptions.TypeError'>,
     <type 'exceptions.UnboundLocalError'>,
     <type 'exceptions.UnicodeDecodeError'>,
     <type 'exceptions.UnicodeEncodeError'>,
     <type 'exceptions.UnicodeError'>,
     <type 'exceptions.UnicodeTranslateError'>,
     <type 'exceptions.UnicodeWarning'>,
     <type 'exceptions.UserWarning'>,
     <type 'exceptions.ValueError'>,
     <type 'exceptions.Warning'>,
     <type 'exceptions.ZeroDivisionError'>,
     <type 'file'>,
     <type 'float'>,
     <type 'frozenset'>,
     <type 'int'>,
     <type 'list'>,
     <type 'long'>,
     <type 'object'>,
     <type 'property'>,
     <type 'reversed'>,
     <type 'set'>,
     <type 'slice'>,
     <type 'staticmethod'>,
     <type 'str'>,
     <type 'str'>,
     <type 'super'>,
     <type 'tuple'>,
     <type 'type'>,
     <type 'unicode'>,
     <type 'xrange'>]
    
        2
  •  4
  •   snoob dogg    8 年前

    @tzot答案不能与Python3.x一起使用,因为 __builtin__ builtin

    try :
        import __builtin__
    except: 
        # Python 3.x
        import builtins
    
    try : 
        builtin_types = [t for t in __builtin__.__dict__.itervalues() if isinstance(t, type)]
    except:
        builtin_types = [getattr(builtins, d) for d in dir(builtins) if isinstance(getattr(builtins, d), type)]
    

    现在使用Python 3.x:

    >>> from pprint import pprint 
    >>> pprint(builtin_types)
    [<class 'ArithmeticError'>,
     <class 'AssertionError'>,
     <class 'AttributeError'>,
     <class 'BaseException'>,
     <class 'BlockingIOError'>,
     <class 'BrokenPipeError'>,
     <class 'BufferError'>,
     <class 'BytesWarning'>,
     <class 'ChildProcessError'>,
     <class 'ConnectionAbortedError'>,
     <class 'ConnectionError'>,
     <class 'ConnectionRefusedError'>,
     <class 'ConnectionResetError'>,
     <class 'DeprecationWarning'>,
     <class 'EOFError'>,
     <class 'OSError'>,
     <class 'Exception'>,
     <class 'FileExistsError'>,
     <class 'FileNotFoundError'>,
     <class 'FloatingPointError'>,
     <class 'FutureWarning'>,
     <class 'GeneratorExit'>,
     <class 'OSError'>,
     <class 'ImportError'>,
     <class 'ImportWarning'>,
     <class 'IndentationError'>,
     <class 'IndexError'>,
     <class 'InterruptedError'>,
     <class 'IsADirectoryError'>,
     <class 'KeyError'>,
     <class 'KeyboardInterrupt'>,
     <class 'LookupError'>,
     <class 'MemoryError'>,
     <class 'NameError'>,
     <class 'NotADirectoryError'>,
     <class 'NotImplementedError'>,
     <class 'OSError'>,
     <class 'OverflowError'>,
     <class 'PendingDeprecationWarning'>,
     <class 'PermissionError'>,
     <class 'ProcessLookupError'>,
     <class 'RecursionError'>,
     <class 'ReferenceError'>,
     <class 'ResourceWarning'>,
     <class 'RuntimeError'>,
     <class 'RuntimeWarning'>,
     <class 'StopAsyncIteration'>,
     <class 'StopIteration'>,
     <class 'SyntaxError'>,
     <class 'SyntaxWarning'>,
     <class 'SystemError'>,
     <class 'SystemExit'>,
     <class 'TabError'>,
     <class 'TimeoutError'>,
     <class 'TypeError'>,
     <class 'UnboundLocalError'>,
     <class 'UnicodeDecodeError'>,
     <class 'UnicodeEncodeError'>,
     <class 'UnicodeError'>,
     <class 'UnicodeTranslateError'>,
     <class 'UnicodeWarning'>,
     <class 'UserWarning'>,
     <class 'ValueError'>,
     <class 'Warning'>,
     <class 'OSError'>,
     <class 'ZeroDivisionError'>,
     <class '_frozen_importlib.BuiltinImporter'>,
     <class 'bool'>,
     <class 'bytearray'>,
     <class 'bytes'>,
     <class 'classmethod'>,
     <class 'complex'>,
     <class 'dict'>,
     <class 'enumerate'>,
     <class 'filter'>,
     <class 'float'>,
     <class 'frozenset'>,
     <class 'int'>,
     <class 'list'>,
     <class 'map'>,
     <class 'memoryview'>,
     <class 'object'>,
     <class 'property'>,
     <class 'range'>,
     <class 'reversed'>,
     <class 'set'>,
     <class 'slice'>,
     <class 'staticmethod'>,
     <class 'str'>,
     <class 'super'>,
     <class 'tuple'>,
     <class 'type'>,
     <class 'zip'>]
    

    你可以做到:

    >>> a = "foo"
    >>> type(a) in builtin_types 
    True
    
        3
  •  1
  •   Ignacio Vazquez-Abrams    16 年前

    存在 relational special methods 不足以保证可比性;如果这些方法不喜欢传递给它们的特定类型,它们仍然可以引发异常。