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

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.

主站蜘蛛池模板: 恩施市| 神池县| 嵊泗县| 花垣县| 新竹市| 恩施市| 宽甸| 建德市| 汝阳县| 秦皇岛市| 安义县| 新兴县| 荣昌县| 宜城市| 栖霞市| 海门市| 六盘水市| 阆中市| 宕昌县| 瓮安县| 三河市| 阆中市| 新民市| 石泉县| 吴堡县| 赫章县| 胶州市| 苏尼特右旗| 朝阳市| 贵港市| 梁山县| 安泽县| 柯坪县| 岳阳市| 五大连池市| 两当县| 长春市| 大兴区| 霸州市| 上思县| 武汉市|