6.3 dir() 函数

内建的函数 dir() 用来找出一个模块定义了哪个名字。它返回一个有序的字符串列表:

  1. >>> import fibo, sys
  2. >>> dir(fibo)
  3. ['__name__', 'fib', 'fib2']
  4. >>> dir(sys)
  5. ['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
  6. '__package__', '__stderr__', '__stdin__', '__stdout__',
  7. '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
  8. '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
  9. 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
  10. 'call_tracing', 'callstats', 'copyright', 'displayhook',
  11. 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
  12. 'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
  13. 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
  14. 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
  15. 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
  16. 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
  17. 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
  18. 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
  19. 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
  20. 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
  21. 'thread_info', 'version', 'version_info', 'warnoptions']

如果没有加参数,dir() 就会列出你当前已经定义过的名字:

  1. >>> a = [1, 2, 3, 4, 5]
  2. >>> import fibo
  3. >>> fib = fibo.fib
  4. >>> dir()
  5. ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

注意,它列出了所有的名字类型:变量、模块、函数等等。

dir() 不会列出内建函数和变量的名字。如果你想列出它们,他们定义在标准模块 builtins 中:

  1. >> import builtins
  2. >>> dir(builtins)
  3. ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
  4. 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
  5. 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
  6. 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
  7. 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
  8. 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
  9. 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
  10. 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
  11. 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
  12. 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
  13. 'NotImplementedError', 'OSError', 'OverflowError',
  14. 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
  15. 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
  16. 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
  17. 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
  18. 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
  19. 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
  20. 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
  21. '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
  22. 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
  23. 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
  24. 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
  25. 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
  26. 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
  27. 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
  28. 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
  29. 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
  30. 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
  31. 'zip']