- Daniel Arbuckle's Mastering Python
- Daniel Arbuckle
- 349字
- 2025-04-04 18:57:48
Importing all package modules
If we want Python to be able to import all the package's modules using import* syntax, we have to tell it the names of all those modules.
To do this, we add the module names to a list called __all__ in the init file as shown in the following code:

sudo apt install emacs24
In the preceding screenshot, I have used Ubuntu, thus the editor is white background, however in case of Windows OS and macOS, the background of the editor can be different.
You might be wondering why we need to do this manually rather than Python just scanning the filesystem for module files.
Well, there are a couple of reasons:
- First, Python tries not to make any assumptions about whether filenames are case-sensitive or not. On some operating systems, filenames are case-sensitive and on other operating systems they are not. Module names are variables, so it's better they originate within the source code, rather than depending on something external that might change depending on where the code is run.
- The second reason for doing this manually is that importing a module makes code execute.
Imagine we have a package that plays soundtracks. In addition to the general purpose code, we also have a bunch of modules that handle audio output on various systems.
Allowing our users to do an import* to bring their packages' programming interface into their module is quite reasonable; however, we don't want all of the output modules to load, just the one that's appropriate to the system we're running on. Trying to load any of the others would most likely trigger an exception in the user's code. The way __all__ works now, we can exclude the output modules from import* and get the best of both worlds.
Alright, let's make sure that Python is willing to import our demo package before we move on to the next part, which is how to add source code modules to a package.