import a.b also imports a?

后端 未结 4 1280
故里飘歌
故里飘歌 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 04:08

    There's an important thing to know about packages, that is that there is a difference between being loaded and being available.

    With import a you load module a (which can be a package) and make it available under the name a.

    With from a import b you load module a (which definitely is a package), then load module a.b and make only this available under the name b. Notice that a also got loaded in the process, so any initialization this is supposed to do will have happened.

    With import a.b you load both and make both available (under the names a and a.b).

提交回复
热议问题