- Daniel Arbuckle's Mastering Python
- Daniel Arbuckle
- 349字
- 2021-07-02 21:09:38
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.
- Learn ECMAScript(Second Edition)
- 少兒人工智能趣味入門:Scratch 3.0動畫與游戲編程
- 一步一步學(xué)Spring Boot 2:微服務(wù)項目實戰(zhàn)
- AngularJS Testing Cookbook
- PyTorch Artificial Intelligence Fundamentals
- UVM實戰(zhàn)
- 利用Python進(jìn)行數(shù)據(jù)分析
- 現(xiàn)代C++編程實戰(zhàn):132個核心技巧示例(原書第2版)
- Vue.js 2 Web Development Projects
- Java SE實踐教程
- Moodle 3 Administration(Third Edition)
- Python硬件編程實戰(zhàn)
- Learning Kotlin by building Android Applications
- Python機器學(xué)習(xí)開發(fā)實戰(zhàn)
- Elastix Unified Communications Server Cookbook