官术网_书友最值得收藏!

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:

If you don't have emacs installed on your system, you can install it by using the following command:

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.

主站蜘蛛池模板: 明水县| 惠水县| 娱乐| 冕宁县| 额济纳旗| 汾阳市| 灵寿县| 宽城| 和静县| 阿拉尔市| 锦屏县| 修武县| 桐城市| 石景山区| 日喀则市| 浦东新区| 金平| 清远市| 廊坊市| 萨迦县| 双鸭山市| 民乐县| 嵊泗县| 青龙| 康平县| 图木舒克市| 南郑县| 黄骅市| 南京市| 丹江口市| 进贤县| 汤阴县| 阳东县| 大英县| 双流县| 康乐县| 清水河县| 正蓝旗| 平山县| 合江县| 宜宾市|