import a.b also imports a?

后端 未结 4 1233
故里飘歌
故里飘歌 2021-02-20 03:26

When I import a subpackage in a package, can I rely on the fact that the parent package is also imported ?

e.g. this works

python -c \"import os.path; pr         


        
4条回答
  •  迷失自我
    2021-02-20 03:57

    This is a good question. If you look at the source code for os.py you find this line:

    sys.modules['os.path'] = path
    

    So there's our module. But what's path? Well that depends on your OS. For Windows, it's defined in this block:

    elif 'nt' in _names:
        name = 'nt'
        linesep = '\r\n'
        from nt import *
        try:
            from nt import _exit
        except ImportError:
            pass
        import ntpath as path
    
        import nt
        __all__.extend(_get_exports_list(nt))
        del nt
    

    Basically, os.path is special in this context.

    Short version: Python does some stuff behind the scenes to make os.path. You probably shouldn't rely on it to get other modules. "Explicit is better than implicit" is how the zen goes.

提交回复
热议问题