简体   繁体   中英

What is the meaning of importing a complete package or a sub-package and not a module inside the package?

I'm refining my original question (thus I edited the post):

Let's assume that we have a package called "PackageA". Inside that package, we have a sub-package called "SubPackageA". Inside that sub-package, we have a module called "ModuleA", and this module includes a function called "functionA".

I understand that in order to call this function, I have to do the following import:

import PackageA.SubPackageA.ModuleA

Then, I can call the function by writing:

PackageA.SubPackageA.ModuleA.functionA()

I also understand that I can do:

from PackageA.SubPackageA.ModuleA import functionA

And then I can call the function by writing:

ModuleA.functionA()

The thing that is not clear to me is: It's possible to import the package, and/or the sub-package by writing:

import PackageA

import PackageA.SubPackageA

But what do I gain by doing that? After all, to be able to call "functionA" I must specifically import the module, so what do I gain by importing the complete package and/or the complete sub-package?

Thanks, Tal.

I'm trying to answer my own question with further research that I made. Let's ignore the sub-package to make it easier.

Let's assume that I have "PackageA" and inside this package, I have a module called "ModuleA" which includes a function called "functionA".

Instead of writing: "import PackageA.ModuleA" in my main file, I can write, in the PackageA dunder init file this: "from PackageA import ModuleA", and then in my main file, I could simply write: "import PackageA" and still be able to call the function (by writing PackageA.ModuleA.functionA()".

This doesn't make sense if you have one module inside your package, but the whole idea of using packages is to combine together multiple modules which are related to each other, and if you import all of the modules from the package's dunder init file, then in your code (main file), you can access all of the functions from all of the modules, simply by importing just package, instead of importing each and each module separately.

Am I right?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM