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

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.

主站蜘蛛池模板: 湘潭县| 涟源市| 托克逊县| 定安县| 陵川县| 甘孜县| 绍兴市| 邵阳县| 怀远县| 元阳县| 错那县| 阳朔县| 余庆县| 陕西省| 布拖县| 安国市| 新干县| 西贡区| 景洪市| 青州市| 济源市| 昌黎县| 嵩明县| 盐池县| 依兰县| 和平县| 阳新县| 德钦县| 丰台区| 七台河市| 南溪县| 开远市| 英吉沙县| 舟曲县| 娄烦县| 沅陵县| 通辽市| 芦山县| 互助| 手游| 离岛区|