Why are there dummy modules in sys.modules?

后端 未结 1 424
清歌不尽
清歌不尽 2020-12-02 01:42

Importing the standard \"logging\" module pollutes sys.modules with a bunch of dummy entries:

Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32         


        
相关标签:
1条回答
  • 2020-12-02 02:24

    None values in sys.modules are cached failures of relative lookups.

    So when you're in package foo and you import sys, Python looks first for a foo.sys module, and if that fails goes to the top-level sys module. To avoid having to check the filesystem for foo/sys.py again on further relative imports, it stores None in the sys.modules to flag that the module didn't exist and a subsequent import shouldn't look there again, but go straight to the loaded sys.

    This is a cPython implementation detail you can't usefully rely on, but you will need to know it if you're doing nasty magic import/reload hacking.

    It happens to all packages, not just logging. For example, import xml.dom and see xml.dom.xml in the module list as it tries to import xml from inside xml.dom.

    As Python moves towards absolute import this ugliness will happen less.

    0 讨论(0)
提交回复
热议问题