6. Modules模块

If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. 如果退出Python解释器并再次输入它,那么所做的定义(函数和变量)将丢失。Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. 因此,如果想编写更长的程序,最好使用文本编辑器为解释器准备输入,并将该文件作为输入运行。This is known as creating a script. 这被称为创建脚本As your program gets longer, you may want to split it into several files for easier maintenance. 随着程序越来越长,您可能希望将其拆分为多个文件以便于维护。You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.您可能还希望使用一个在多个程序中编写的方便函数,而无需将其定义复制到每个程序中。

To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. 为了支持这一点,Python可以将定义放在文件中,并在脚本或解释器的交互式实例中使用它们。Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).这样的文件称为模块;模块中的定义可以导入到其他模块或模块中(在顶层以计算器模式执行的脚本中可以访问的变量集合)。

A module is a file containing Python definitions and statements. 模块是包含Python定义和语句的文件。The file name is the module name with the suffix .py appended. 文件名是附加了后缀.py的模块名。Within a module, the module’s name (as a string) is available as the value of the global variable __name__. 在模块中,模块名称(作为字符串)可用作全局变量__name__的值。For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:例如,使用您最喜欢的文本编辑器在当前目录中创建一个名为fico.py的文件,其中包含以下内容:

# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()

def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result

Now enter the Python interpreter and import this module with the following command:现在进入Python解释器,并使用以下命令导入此模块:

>>> import fibo

This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. 这不会在当前符号表中直接输入fibo中定义的函数名称;它只在那里输入模块名fiboUsing the module name you can access the functions:使用模块名称可以访问以下功能:

>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

If you intend to use a function often you can assign it to a local name:如果要经常使用某个函数,可以将其指定给本地名称:

>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

6.1. More on Modules详解模块

A module can contain executable statements as well as function definitions. 模块可以包含可执行语句和函数定义。These statements are intended to initialize the module. 这些语句用于初始化模块。They are executed only the first time the module name is encountered in an import statement. 它们仅在import语句中第一次遇到模块名时执行。1 (They are also run if the file is executed as a script.)(如果文件作为脚本执行,它们也会运行。)

Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. 每个模块都有自己的专用符号表,该表由模块中定义的所有函数用作全局符号表。Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. 因此,模块的作者可以在模块中使用全局变量,而不用担心与用户的全局变量发生意外冲突。On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.另一方面,如果你知道自己在做什么,你可以用与模块函数相同的符号modname.itemname来触摸模块的全局变量。

Modules can import other modules. 模块可以导入其他模块。It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). 按照惯例,但不要求将所有import语句放在模块(或脚本)的开头。The imported module names are placed in the importing module’s global symbol table.导入的模块名称放置在导入模块的全局符号表中。

There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table. import语句的一个变体是将模块中的名称直接导入导入模块的符号表中。For example:例如:

>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined).这不会在本地符号表中引入导入的模块名(因此在本例中,未定义fibo)。

There is even a variant to import all names that a module defines:甚至还有一个变量可以导入模块定义的所有名称:

>>> from fibo import *
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore (_). 这将导入所有名称,但以下划线(_)开头的名称除外。In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.在大多数情况下,Python程序员不使用此功能,因为它会在解释器中引入一组未知的名称,可能会隐藏一些您已经定义的内容。

Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. 请注意,通常不赞成从模块或包导入*的做法,因为这通常会导致代码可读性差。However, it is okay to use it to save typing in interactive sessions.但是,可以使用它来保存交互式会话中的输入。

If the module name is followed by as, then the name following as is bound directly to the imported module.如果模块名后面跟着as,那么as后面的名称将直接绑定到导入的模块。

>>> import fibo as fib
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This is effectively importing the module in the same way that import fibo will do, with the only difference of it being available as fib.这实际上是以import fibo的相同方式导入模块,唯一的区别是它可以作为fib使用。

It can also be used when utilising from with similar effects:当使用具有类似效果的from时,也可以使用它:

>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Note

For efficiency reasons, each module is only imported once per interpreter session. 出于效率考虑,每个模块在每个解释器会话中只导入一次。Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload(), e.g. import importlib; importlib.reload(modulename).因此,如果更改模块,必须重新启动解释器——或者,如果只是一个要交互测试的模块,请使用importlib.reload(),例如import importlib; importlib.reload(modulename)

6.1.1. Executing modules as scripts以脚本形式执行模块

When you run a Python module with在运行Python模块时

python fibo.py <arguments>

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". 模块中的代码将被执行,就像您导入它一样,但是__name__设置为"__main__"That means that by adding this code at the end of your module:这意味着通过在模块末尾添加以下代码:

if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))

you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:您可以将该文件用作脚本和可导入模块,因为只有当该模块作为“主”文件执行时,解析命令行的代码才会运行:

$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34

If the module is imported, the code is not run:如果导入模块,则代码不会运行:

>>> import fibo
>>>

This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).这通常用于为模块提供方便的用户界面,或用于测试目的(以脚本执行测试套件的方式运行模块)。

6.1.2. The Module Search Path模块搜索路径

When a module named spam is imported, the interpreter first searches for a built-in module with that name. 导入名为spam的模块时,解释器首先搜索具有该名称的内置模块。If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. 如果找不到,它会在变量sys.path给出的目录列表中搜索名为spam.py的文件。sys.path is initialized from these locations:从以下位置初始化:

  • The directory containing the input script (or the current directory when no file is specified).包含输入脚本的目录(或未指定文件时的当前目录)。

  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).(目录名列表,语法与shell变量PATH相同)。

  • The installation-dependent default (by convention including a site-packages directory, handled by the site module).依赖于安装的默认设置(按照惯例,包括由site模块处理的site-packages目录)。

Note

On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. 在支持符号链接的文件系统上,包含输入脚本的目录在符号链接之后计算。In other words the directory containing the symlink is not added to the module search path.换句话说,包含符号链接的目录不会添加到模块搜索路径中。

After initialization, Python programs can modify sys.path. 初始化之后,Python程序可以修改sys.pathThe directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. 包含正在运行的脚本的目录位于搜索路径的开头,位于标准库路径之前。This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. 这意味着将加载该目录中的脚本,而不是库目录中同名的模块。This is an error unless the replacement is intended. 除非有意更换,否则这是一个错误。See section Standard Modules for more information.有关更多信息,请参阅标准模块一节。

6.1.3. “Compiled” Python files“已编译的”Python文件

To speed up loading modules, Python caches the compiled version of each module in the __pycache__ directory under the name module.version.pyc, where the version encodes the format of the compiled file; it generally contains the Python version number. 为了加快加载模块的速度,Python将每个模块的编译版本缓存在__pycache__目录下的module.version.pyc下,该版本对编译文件的格式进行编码;它通常包含Python版本号。For example, in CPython release 3.3 the compiled version of spam.py would be cached as __pycache__/spam.cpython-33.pyc. 例如,在CPython 3.3版中,spam.py的编译版本将被缓存为__pycache__/spam.cpython-33.pycThis naming convention allows compiled modules from different releases and different versions of Python to coexist.这种命名约定允许来自不同版本Python的编译模块共存。

Python checks the modification date of the source against the compiled version to see if it’s out of date and needs to be recompiled. Python会根据编译后的版本检查源代码的修改日期,看它是否过时,是否需要重新编译。This is a completely automatic process. 这是一个完全自动的过程。Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures.此外,编译后的模块与平台无关,因此可以在具有不同体系结构的系统之间共享同一个库。

Python does not check the cache in two circumstances. Python在两种情况下不检查缓存。First, it always recompiles and does not store the result for the module that’s loaded directly from the command line. 首先,它总是重新编译,不存储直接从命令行加载的模块的结果。Second, it does not check the cache if there is no source module. 其次,如果没有源模块,它不会检查缓存。To support a non-source (compiled only) distribution, the compiled module must be in the source directory, and there must not be a source module.要支持非源(仅编译)发行版,编译的模块必须位于源目录中,并且不能有源模块。

Some tips for experts:给专家的一些建议:

  • You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. 可以在Python命令上使用-O-OO开关来减小已编译模块的大小。The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings. -O开关删除断言语句,-OO开关同时删除断言语句和__doc__字符串。Since some programs may rely on having these available, you should only use this option if you know what you’re doing. 由于一些程序可能依赖于这些可用的程序,所以只有在您知道自己在做什么的情况下,才应该使用此选项。“Optimized” modules have an opt- tag and are usually smaller. “已优化”模块有一个opt-标签,通常较小。Future releases may change the effects of optimization.未来的版本可能会改变优化的效果。

  • A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded..pyc文件读取程序时,其运行速度不会比从.py文件读取程序时快;.pyc文件唯一更快的地方就是加载速度。

  • The module compileall can create .pyc files for all modules in a directory.模块compileall可以为目录中的所有模块创建.pyc文件。

  • There is more detail on this process, including a flow chart of the decisions, in PEP 3147.PEP 3147中有关于这一过程的更多细节,包括决策流程图。

6.2. Standard Modules标准模块

Python comes with a library of standard modules, described in a separate document, the Python Library Reference (“Library Reference” hereafter). Python附带了一个标准模块库,在另一个文档《Python库参考》(以下简称“库参考”)中进行了描述。Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. 解释器内置了一些模块;它们提供对不属于语言核心的操作的访问,但这些操作是内置的,无论是为了提高效率,还是为了提供对操作系统原语(如系统调用)的访问。The set of such modules is a configuration option which also depends on the underlying platform. 这组模块是一个配置选项,也取决于底层平台。For example, the winreg module is only provided on Windows systems. 例如,winreg模块仅在Windows系统上提供。One particular module deserves some attention: sys, which is built into every Python interpreter. 有一个特别的模块值得注意:sys,它内置于每个Python解释器中。The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:变量sys.ps1sys.ps2定义了用作主要和次要提示的字符串:

>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>

These two variables are only defined if the interpreter is in interactive mode.只有当解释器处于交互模式时,才定义这两个变量。

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. 变量sys.path是一个字符串列表,用于确定解释器对模块的搜索路径。It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. 它被初始化为从环境变量PYTHONPATH获取的默认路径,或者如果未设置PYTHONPATH,则从内置默认路径获取。You can modify it using standard list operations:可以使用标准列表操作对其进行修改:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

6.3. The dir() Functiondir()函数

The built-in function dir() is used to find out which names a module defines. 内置函数dir()用于找出模块定义的名称。It returns a sorted list of strings:它返回一个已排序的字符串列表:

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
'__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
'__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
'_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',
'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',
'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',
'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',
'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',
'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',
'warnoptions']

Without arguments, dir() lists the names you have defined currently:如果没有参数,dir()将列出您当前定义的名称:

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

Note that it lists all types of names: variables, modules, functions, etc.请注意,它列出了所有类型的名称:变量、模块、函数等。

dir() does not list the names of built-in functions and variables. 不列出内置函数和变量的名称。If you want a list of those, they are defined in the standard module builtins:如果您想要这些功能的列表,请在标准模块builtins中定义:

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
'zip']

6.4. Packages

Packages are a way of structuring Python’s module namespace by using “dotted module names”. 包是一种通过使用“虚线模块名称”构造Python模块名称空间的方法。For example, the module name A.B designates a submodule named B in a package named A. 例如,模块名A.B在名为A的包中指定名为B的子模块。Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names.就像使用模块可以让不同模块的作者不用担心彼此的全局变量名一样,使用虚线模块名也可以让多模块包(如NumPy或Pillow)的作者不用担心彼此的模块名。

Suppose you want to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. 假设您想要设计一个模块集合(“包”),以便统一处理声音文件和声音数据。There are many different sound file formats (usually recognized by their extension, for example: .wav, .aiff, .au), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. 有许多不同的声音文件格式(通常通过扩展名识别,例如:.wav.aiff.au),因此您可能需要创建和维护越来越多的模块集合,以便在各种文件格式之间进行转换。There are also many different operations you might want to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform these operations. 您可能还需要对声音数据执行许多不同的操作(例如混音、添加回声、应用均衡器功能、创建人造立体声效果),因此,除此之外,您还需要编写一个永无止境的模块流来执行这些操作。Here’s a possible structure for your package (expressed in terms of a hierarchical filesystem):下面是您的包的可能结构(用分层文件系统表示):

sound/                          Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.导入包时,Python会在sys.path上的目录中搜索包的子目录。

The __init__.py files are required to make Python treat directories containing the file as packages. 需要__init__.py文件才能使Python将包含该文件的目录视为包。This prevents directories with a common name, such as string, unintentionally hiding valid modules that occur later on the module search path. 这可以防止具有公共名称(如string)的目录无意中隐藏模块搜索路径上稍后出现的有效模块。In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.在最简单的情况下,__init__.py可以只是一个空文件,但它也可以执行包的初始化代码,或者设置__all__变量,后面将介绍。

Users of the package can import individual modules from the package, for example:包的用户可以从包中导入单个模块,例如:

import sound.effects.echo

This loads the submodule sound.effects.echo. 这将加载子模块sound.effects.echoIt must be referenced with its full name.必须使用其全名引用它。

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

An alternative way of importing the submodule is:导入子模块的另一种方法是:

from sound.effects import echo

This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:这也会加载子模块echo,并使其在没有包前缀的情况下可用,因此可以按如下方式使用:

echo.echofilter(input, output, delay=0.7, atten=4)

Yet another variation is to import the desired function or variable directly:另一种变体是直接导入所需的函数或变量:

from sound.effects.echo import echofilter

Again, this loads the submodule echo, but this makes its function echofilter() directly available:同样,这会加载子模块echo,但这会使其函数echofilter()直接可用:

echofilter(input, output, delay=0.7, atten=4)

Note that when using from package import item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. 请注意,使用from package import item时,该项可以是包的子模块(或子包),也可以是包中定义的其他名称,如函数、类或变量。The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. import语句首先测试包中是否定义了该项;如果不是,则假定它是一个模块,并尝试加载它。If it fails to find it, an ImportError exception is raised.如果找不到,则会引发ImportError异常。

Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.相反,当使用像import item.subitem.subsubitem这样的语法时,除了最后一项之外,每个项都必须是一个包;最后一项可以是模块或包,但不能是前一项中定义的类、函数或变量。

6.4.1. Importing * From a Package从包中导入*

Now what happens when the user writes from sound.effects import *? 现在,当用户写了from sound.effects import *时会发生什么?Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. 在理想情况下,我们希望它以某种方式进入文件系统,找到包中存在哪些子模块,并将它们全部导入。This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.这可能需要很长时间,并且导入子模块可能会产生不必要的副作用,这种副作用只有在显式导入子模块时才会发生。

The only solution is for the package author to provide an explicit index of the package. 唯一的解决方案是由包作者提供包的显式索引。The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. import语句使用以下约定:如果包的__init__.py代码定义了一个名为__all__的列表,则当遇到“从包导入”时,它被视为应该导入的模块名称列表。It is up to the package author to keep this list up-to-date when a new version of the package is released. 当软件包的新版本发布时,由软件包作者更新此列表。Package authors may also decide not to support it, if they don’t see a use for importing * from their package. 如果包作者认为从包中导入*没有用,他们也可能决定不支持它。For example, the file sound/effects/__init__.py could contain the following code:例如,文件sound/effects/_init__.py可能包含以下代码:

__all__ = ["echo", "surround", "reverse"]

This would mean that from sound.effects import * would import the three named submodules of the sound.effects package.这意味着from sound.effects import *将导入sound.effects包的三个子模块。

If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. 如果未定义__all__from sound.effects import *语句不会sound.effects包中的所有子模块导入当前命名空间;它只确保已导入包sound.effects(可能运行__init__.py中的任何初始化代码),然后导入包中定义的任何名称。This includes any names defined (and submodules explicitly loaded) by __init__.py. 这包括由__init__.py定义的任何名称(以及显式加载的子模块)。It also includes any submodules of the package that were explicitly loaded by previous import statements. 它还包括以前的import语句显式加载的包的任何子模块。Consider this code:考虑以下代码:

import sound.effects.echo
import sound.effects.surround
from sound.effects import *

In this example, the echo and surround modules are imported in the current namespace because they are defined in the sound.effects package when the from...import statement is executed. (This also works when __all__ is defined.)在本例中,echosurround模块在当前名称空间中导入,因为当执行from...import语句时,是在sound.effects包中定义它们的。(定义了__all__时也可以起作用。)

Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practice in production code.尽管某些模块被设计为在使用import *时只导出遵循某些模式的名称,但在生产代码中,这仍然被认为是不好的做法。

Remember, there is nothing wrong with using from package import specific_submodule! 记住,使用from package import specific_submodule并没有错!In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages.事实上,除非导入模块需要使用来自不同包的同名子模块,否则这是推荐的符号。

6.4.2. Intra-package References包内引用

When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. 当包被构造成子包时(与示例中的sound包一样),可以使用绝对导入来引用同级包的子模块。For example, if the module sound.filters.vocoder needs to use the echo module in the sound.effects package, it can use from sound.effects import echo.例如,如果模块sound.filters.vocoder需要使用sound.effects软件包中的echo模块,它可以使用from sound.effects import echo

You can also write relative imports, with the from module import name form of import statement. 还可以使用import语句的from module import name形式编写相对导入。These imports use leading dots to indicate the current and parent packages involved in the relative import. 这些导入使用前导点来指示相对导入中涉及的当前和父包。From the surround module for example, you might use:例如,在surround模块中,您可以使用:

from . import echo
from .. import formats
from ..filters import equalizer

Note that relative imports are based on the name of the current module. 请注意,相对导入基于当前模块的名称。Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.由于主模块的名称始终以"__main__"的形式主调用,因此用作Python应用程序主模块的模块必须始终使用绝对导入。

6.4.3. Packages in Multiple Directories多个目录中的包

Packages support one more special attribute, __path__. 包还支持一个特殊属性,即__path__This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. 它被初始化为一个列表,其中包含在执行该文件中的代码之前保存包的__init__.py的目录的名称。This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.这个变量可以修改;这样做会影响将来对包中包含的模块和子包的搜索。

While this feature is not often needed, it can be used to extend the set of modules found in a package.虽然这个特性并不经常需要,但它可以用来扩展包中的模块集。

Footnotes

1

In fact function definitions are also ‘statements’ that are ‘executed’; the execution of a module-level function definition enters the function name in the module’s global symbol table.实际上,函数定义也是“执行”的“语句”;执行模块级函数定义时,在模块的全局符号表中输入函数名。