# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # python-doc bot, 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.11\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-01-03 15:28+0000\n" "PO-Revision-Date: 2025-09-22 16:51+0000\n" "Last-Translator: python-doc bot, 2025\n" "Language-Team: Chinese (China) (https://app.transifex.com/python-doc/teams/5390/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../reference/import.rst:6 msgid "The import system" msgstr "导入系统" #: ../../reference/import.rst:10 msgid "" "Python code in one :term:`module` gains access to the code in another module" " by the process of :term:`importing` it. The :keyword:`import` statement is" " the most common way of invoking the import machinery, but it is not the " "only way. Functions such as :func:`importlib.import_module` and built-in " ":func:`__import__` can also be used to invoke the import machinery." msgstr "" "一个 :term:`module` 内的 Python 代码通过 :term:`importing` 操作就能够访问另一个模块内的代码。 " ":keyword:`import` 语句是唤起导入机制的最常用方式,但不是唯一的方式。 :func:`importlib.import_module` " "以及内置的 :func:`__import__` 等函数也可以被用来唤起导入机制。" #: ../../reference/import.rst:16 msgid "" "The :keyword:`import` statement combines two operations; it searches for the" " named module, then it binds the results of that search to a name in the " "local scope. The search operation of the :keyword:`!import` statement is " "defined as a call to the :func:`__import__` function, with the appropriate " "arguments. The return value of :func:`__import__` is used to perform the " "name binding operation of the :keyword:`!import` statement. See the " ":keyword:`!import` statement for the exact details of that name binding " "operation." msgstr "" ":keyword:`import` 语句结合了两个操作;它先搜索指定名称的模块,然后将搜索结果绑定到当前作用域中的名称。 " ":keyword:`!import` 语句的搜索操作被定义为对 :func:`__import__` 函数的调用并带有适当的参数。 " ":func:`__import__` 的返回值会被用于执行 :keyword:`!import` 语句的名称绑定操作。 请参阅 " ":keyword:`!import` 语句了解名称绑定操作的更多细节。" #: ../../reference/import.rst:25 msgid "" "A direct call to :func:`__import__` performs only the module search and, if " "found, the module creation operation. While certain side-effects may occur," " such as the importing of parent packages, and the updating of various " "caches (including :data:`sys.modules`), only the :keyword:`import` statement" " performs a name binding operation." msgstr "" "对 :func:`__import__` 的直接调用将仅执行模块搜索以及在找到时的模块创建操作。 不过也可能产生某些副作用,例如导入父包和更新各种缓存 " "(包括 :data:`sys.modules`),只有 :keyword:`import` 语句会执行名称绑定操作。" #: ../../reference/import.rst:31 msgid "" "When an :keyword:`import` statement is executed, the standard builtin " ":func:`__import__` function is called. Other mechanisms for invoking the " "import system (such as :func:`importlib.import_module`) may choose to bypass" " :func:`__import__` and use their own solutions to implement import " "semantics." msgstr "" "当 :keyword:`import` 语句被执行时,标准的内置 :func:`__import__` 函数会被调用。 其他唤起导入系统的机制 (例如 " ":func:`importlib.import_module`) 可能会选择绕过 :func:`__import__` " "并使用它们自己的解决方案来实现导入机制。" #: ../../reference/import.rst:36 msgid "" "When a module is first imported, Python searches for the module and if " "found, it creates a module object [#fnmo]_, initializing it. If the named " "module cannot be found, a :exc:`ModuleNotFoundError` is raised. Python " "implements various strategies to search for the named module when the import" " machinery is invoked. These strategies can be modified and extended by " "using various hooks described in the sections below." msgstr "" "当一个模块首次被导入时,Python 会搜索该模块,如果找到就创建一个 module 对象 [#fnmo]_ 并初始化它。 " "如果指定名称的模块未找到,则会引发 :exc:`ModuleNotFoundError`。 当唤起导入机制时,Python " "会实现多种策略来搜索指定名称的模块。 这些策略可以通过使用使用下文所描述的多种钩子来加以修改和扩展。" #: ../../reference/import.rst:43 msgid "" "The import system has been updated to fully implement the second phase of " ":pep:`302`. There is no longer any implicit import machinery - the full " "import system is exposed through :data:`sys.meta_path`. In addition, native " "namespace package support has been implemented (see :pep:`420`)." msgstr "" "导入系统已被更新以完全实现 :pep:`302` 中的第二阶段要求。 不会再有任何隐式的导入机制 —— 整个导入系统都通过 " ":data:`sys.meta_path` 暴露出来。 此外,对原生命名空间包的支持也已被实现 (参见 :pep:`420`)。" #: ../../reference/import.rst:51 msgid ":mod:`importlib`" msgstr ":mod:`importlib`" #: ../../reference/import.rst:53 msgid "" "The :mod:`importlib` module provides a rich API for interacting with the " "import system. For example :func:`importlib.import_module` provides a " "recommended, simpler API than built-in :func:`__import__` for invoking the " "import machinery. Refer to the :mod:`importlib` library documentation for " "additional detail." msgstr "" ":mod:`importlib` 模块提供了一个丰富的 API 用来与导入系统进行交互。 例如 " ":func:`importlib.import_module` 提供了相比内置的 :func:`__import__` 更推荐、更简单的 API " "用来唤起导入机制。 更多细节请参看 :mod:`importlib` 库文档。" #: ../../reference/import.rst:62 msgid "Packages" msgstr "包" #: ../../reference/import.rst:67 msgid "" "Python has only one type of module object, and all modules are of this type," " regardless of whether the module is implemented in Python, C, or something " "else. To help organize modules and provide a naming hierarchy, Python has a" " concept of :term:`packages `." msgstr "" "Python 只有一种模块对象类型,所有模块都属于该类型,无论模块是用 Python、C 还是别的语言实现。 " "为了帮助组织模块并提供名称层次结构,Python 还引入了 :term:`包 ` 的概念。" #: ../../reference/import.rst:72 msgid "" "You can think of packages as the directories on a file system and modules as" " files within directories, but don't take this analogy too literally since " "packages and modules need not originate from the file system. For the " "purposes of this documentation, we'll use this convenient analogy of " "directories and files. Like file system directories, packages are organized" " hierarchically, and packages may themselves contain subpackages, as well as" " regular modules." msgstr "" "你可以把包看成是文件系统中的目录,并把模块看成是目录中的文件,但请不要对这个类比做过于字面的理解,因为包和模块不是必须来自于文件系统。 " "为了方便理解本文档,我们将继续使用这种目录和文件的类比。 与文件系统一样,包通过层次结构进行组织,在包之内除了一般的模块,还可以有子包。" #: ../../reference/import.rst:80 msgid "" "It's important to keep in mind that all packages are modules, but not all " "modules are packages. Or put another way, packages are just a special kind " "of module. Specifically, any module that contains a ``__path__`` attribute " "is considered a package." msgstr "" "要注意的一个重点概念是所有包都是模块,但并非所有模块都是包。 或者换句话说,包只是一种特殊的模块。 特别地,任何具有 ``__path__`` " "属性的模块都会被当作是包。" #: ../../reference/import.rst:85 msgid "" "All modules have a name. Subpackage names are separated from their parent " "package name by a dot, akin to Python's standard attribute access syntax. " "Thus you might have a package called :mod:`email`, which in turn has a " "subpackage called :mod:`email.mime` and a module within that subpackage " "called :mod:`email.mime.text`." msgstr "" "所有模块都有自己的名字。 子包名与其父包名会以点号分隔,与 Python 的标准属性访问语法一致。 因此你可能会有一个名为 :mod:`email` " "的包,这个包中又有一个名为 :mod:`email.mime` 的子包以及该子包中的名为 :mod:`email.mime.text` 的子包。" #: ../../reference/import.rst:93 msgid "Regular packages" msgstr "常规包" #: ../../reference/import.rst:98 msgid "" "Python defines two types of packages, :term:`regular packages ` and :term:`namespace packages `. Regular " "packages are traditional packages as they existed in Python 3.2 and earlier." " A regular package is typically implemented as a directory containing an " "``__init__.py`` file. When a regular package is imported, this " "``__init__.py`` file is implicitly executed, and the objects it defines are " "bound to names in the package's namespace. The ``__init__.py`` file can " "contain the same Python code that any other module can contain, and Python " "will add some additional attributes to the module when it is imported." msgstr "" "Python 定义了两种类型的包,:term:`常规包 ` 和 :term:`命名空间包 `。 常规包是传统的包类型,它们在 Python 3.2 及之前就已存在。 常规包通常以一个包含 ``__init__.py`` " "文件的目录形式实现。 当一个常规包被导入时,这个 ``__init__.py`` " "文件会隐式地被执行,它所定义的对象会被绑定到该包命名空间中的名称。``__init__.py`` 文件可以包含与任何其他模块中所包含的 Python " "代码相似的代码,Python 将在模块被导入时为其添加额外的属性。" #: ../../reference/import.rst:108 msgid "" "For example, the following file system layout defines a top level ``parent``" " package with three subpackages::" msgstr "例如,以下文件系统布局定义了一个最高层级的 ``parent`` 包和三个子包::" #: ../../reference/import.rst:120 msgid "" "Importing ``parent.one`` will implicitly execute ``parent/__init__.py`` and " "``parent/one/__init__.py``. Subsequent imports of ``parent.two`` or " "``parent.three`` will execute ``parent/two/__init__.py`` and " "``parent/three/__init__.py`` respectively." msgstr "" "导入 ``parent.one`` 将隐式地执行 ``parent/__init__.py`` 和 " "``parent/one/__init__.py``。 后续导入 ``parent.two`` 或 ``parent.three`` 则将分别执行 " "``parent/two/__init__.py`` 和 ``parent/three/__init__.py``。" #: ../../reference/import.rst:127 msgid "Namespace packages" msgstr "命名空间包" #: ../../reference/import.rst:133 msgid "" "A namespace package is a composite of various :term:`portions `, " "where each portion contributes a subpackage to the parent package. Portions" " may reside in different locations on the file system. Portions may also be" " found in zip files, on the network, or anywhere else that Python searches " "during import. Namespace packages may or may not correspond directly to " "objects on the file system; they may be virtual modules that have no " "concrete representation." msgstr "" "命名空间包是由多个 :term:`部分 ` 构成的,每个部分为父包增加一个子包。 各个部分可能处于文件系统的不同位置。 部分也可能处于" " zip 文件中、网络上,或者 Python 在导入期间可以搜索的其他地方。 " "命名空间包并不一定会直接对应到文件系统中的对象;它们有可能是无实体表示的虚拟模块。" #: ../../reference/import.rst:141 msgid "" "Namespace packages do not use an ordinary list for their ``__path__`` " "attribute. They instead use a custom iterable type which will automatically " "perform a new search for package portions on the next import attempt within " "that package if the path of their parent package (or :data:`sys.path` for a " "top level package) changes." msgstr "" "命名空间包的 ``__path__`` 属性不使用普通的列表。 而是使用定制的可迭代类型,如果其父包的路径 (或者最高层级包的 " ":data:`sys.path`) 发生改变,这种对象会在该包内的下一次导入尝试时自动执行新的对包部分的搜索。" #: ../../reference/import.rst:147 msgid "" "With namespace packages, there is no ``parent/__init__.py`` file. In fact, " "there may be multiple ``parent`` directories found during import search, " "where each one is provided by a different portion. Thus ``parent/one`` may " "not be physically located next to ``parent/two``. In this case, Python will" " create a namespace package for the top-level ``parent`` package whenever it" " or one of its subpackages is imported." msgstr "" "命名空间包没有 ``parent/__init__.py`` 文件。 实际上,在导入搜索期间可能找到多个 ``parent`` " "目录,每个都由不同的部分所提供。 因此 ``parent/one`` 的物理位置不一定与 ``parent/two`` 相邻。 " "在这种情况下,Python 将为顶级的 ``parent`` 包创建一个命名空间包,无论是它本身还是它的某个子包被导入。" #: ../../reference/import.rst:154 msgid "See also :pep:`420` for the namespace package specification." msgstr "另请参阅 :pep:`420` 了解对命名空间包的规格描述。" #: ../../reference/import.rst:158 msgid "Searching" msgstr "搜索" #: ../../reference/import.rst:160 msgid "" "To begin the search, Python needs the :term:`fully qualified ` name of the module (or package, but for the purposes of this " "discussion, the difference is immaterial) being imported. This name may " "come from various arguments to the :keyword:`import` statement, or from the " "parameters to the :func:`importlib.import_module` or :func:`__import__` " "functions." msgstr "" "为了开始搜索,Python 需要被导入模块(或者包,对于当前讨论来说两者没有差别)的完整 :term:`限定名称 `。 " "此名称可以来自 :keyword:`import` 语句所带的各种参数,或者来自传给 :func:`importlib.import_module` 或" " :func:`__import__` 函数的形参。" #: ../../reference/import.rst:166 msgid "" "This name will be used in various phases of the import search, and it may be" " the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python" " first tries to import ``foo``, then ``foo.bar``, and finally " "``foo.bar.baz``. If any of the intermediate imports fail, a " ":exc:`ModuleNotFoundError` is raised." msgstr "" "此名称会在导入搜索的各个阶段被使用,它也可以是指向一个子模块的带点号路径,例如 ``foo.bar.baz``。 在这种情况下,Python " "会先尝试导入 ``foo``,然后是 ``foo.bar``,最后是 ``foo.bar.baz``。 如果这些导入中的任何一个失败,都会引发 " ":exc:`ModuleNotFoundError`。" #: ../../reference/import.rst:173 msgid "The module cache" msgstr "模块缓存" #: ../../reference/import.rst:178 msgid "" "The first place checked during import search is :data:`sys.modules`. This " "mapping serves as a cache of all modules that have been previously imported," " including the intermediate paths. So if ``foo.bar.baz`` was previously " "imported, :data:`sys.modules` will contain entries for ``foo``, ``foo.bar``," " and ``foo.bar.baz``. Each key will have as its value the corresponding " "module object." msgstr "" "在导入搜索期间首先会被检查的地方是 :data:`sys.modules`。 这个映射起到缓存之前导入的所有模块的作用(包括其中间路径)。 " "因此如果之前导入过 ``foo.bar.baz``,则 :data:`sys.modules` 将包含 ``foo``, ``foo.bar`` 和 " "``foo.bar.baz`` 条目。 每个键的值就是相应的模块对象。" #: ../../reference/import.rst:185 msgid "" "During import, the module name is looked up in :data:`sys.modules` and if " "present, the associated value is the module satisfying the import, and the " "process completes. However, if the value is ``None``, then a " ":exc:`ModuleNotFoundError` is raised. If the module name is missing, Python" " will continue searching for the module." msgstr "" "在导入期间,会在 :data:`sys.modules` 查找模块名称,如存在则其关联的值就是需要导入的模块,导入过程完成。 然而,如果值为 " "``None``,则会引发 :exc:`ModuleNotFoundError`。 如果找不到指定模块名称,Python 将继续搜索该模块。" #: ../../reference/import.rst:191 msgid "" ":data:`sys.modules` is writable. Deleting a key may not destroy the " "associated module (as other modules may hold references to it), but it will " "invalidate the cache entry for the named module, causing Python to search " "anew for the named module upon its next import. The key can also be assigned" " to ``None``, forcing the next import of the module to result in a " ":exc:`ModuleNotFoundError`." msgstr "" ":data:`sys.modules` 是可写的。删除键可能不会破坏关联的模块(因为其他模块可能会保留对它的引用),但它会使命名模块的缓存条目无效,导致" " Python 在下次导入时重新搜索命名模块。键也可以赋值为 ``None`` ,强制下一次导入模块导致 " ":exc:`ModuleNotFoundError` 。" #: ../../reference/import.rst:198 msgid "" "Beware though, as if you keep a reference to the module object, invalidate " "its cache entry in :data:`sys.modules`, and then re-import the named module," " the two module objects will *not* be the same. By contrast, " ":func:`importlib.reload` will reuse the *same* module object, and simply " "reinitialise the module contents by rerunning the module's code." msgstr "" "但是要小心,因为如果你还保有对某个模块对象的引用,同时停用其在 :data:`sys.modules` " "中的缓存条目,然后又再次导入该名称的模块,则前后两个模块对象将 *不是* 同一个。 相反地,:func:`importlib.reload` 将重用 " "*同一个* 模块对象,并简单地通过重新运行模块的代码来重新初始化模块内容。" #: ../../reference/import.rst:208 msgid "Finders and loaders" msgstr "查找器和加载器" #: ../../reference/import.rst:215 msgid "" "If the named module is not found in :data:`sys.modules`, then Python's " "import protocol is invoked to find and load the module. This protocol " "consists of two conceptual objects, :term:`finders ` and " ":term:`loaders `. A finder's job is to determine whether it can find" " the named module using whatever strategy it knows about. Objects that " "implement both of these interfaces are referred to as :term:`importers " "` - they return themselves when they find that they can load the " "requested module." msgstr "" "如果指定名称的模块在 :data:`sys.modules` 找不到,则将唤起 Python 的导入协议以查找和加载该模块。 " "此协议由两个概念性模块构成,即 :term:`查找器 ` 和 :term:`加载器 `。 " "查找器的任务是确定是否能使用其所知的策略找到该名称的模块。 同时实现这两种接口的对象称为 :term:`导入器 ` —— " "它们在确定能加载所需的模块时会返回其自身。" #: ../../reference/import.rst:223 msgid "" "Python includes a number of default finders and importers. The first one " "knows how to locate built-in modules, and the second knows how to locate " "frozen modules. A third default finder searches an :term:`import path` for " "modules. The :term:`import path` is a list of locations that may name file " "system paths or zip files. It can also be extended to search for any " "locatable resource, such as those identified by URLs." msgstr "" "Python 包含了多个默认查找器和导入器。 第一个知道如何定位内置模块,第二个知道如何定位冻结模块。 第三个默认查找器会在 :term:`import" " path` 中搜索模块。 :term:`import path` 是一个由文件系统路径或 zip 文件组成的位置列表。 " "它还可以扩展为搜索任意可定位资源,例如由 URL 指定的资源。" #: ../../reference/import.rst:230 msgid "" "The import machinery is extensible, so new finders can be added to extend " "the range and scope of module searching." msgstr "导入机制是可扩展的,因此可以加入新的查找器以扩展模块搜索的范围和作用域。" #: ../../reference/import.rst:233 msgid "" "Finders do not actually load modules. If they can find the named module, " "they return a :dfn:`module spec`, an encapsulation of the module's import-" "related information, which the import machinery then uses when loading the " "module." msgstr "" "查找器并不真正加载模块。 如果它们能找到指定名称的模块,会返回一个 " ":dfn:`模块规格说明`,这是对模块导入相关信息的封装,供后续导入机制用于在加载模块时使用。" #: ../../reference/import.rst:237 msgid "" "The following sections describe the protocol for finders and loaders in more" " detail, including how you can create and register new ones to extend the " "import machinery." msgstr "以下各节描述了有关查找器和加载器协议的更多细节,包括你应该如何创建并注册新的此类对象来扩展导入机制。" #: ../../reference/import.rst:241 msgid "" "In previous versions of Python, finders returned :term:`loaders ` " "directly, whereas now they return module specs which *contain* loaders. " "Loaders are still used during import but have fewer responsibilities." msgstr "" "在之前的 Python 版本中,查找器会直接返回 :term:`加载器 `,现在它们则返回模块规格说明,其中 *包含* 加载器。 " "加载器仍然在导入期间被使用,但负担的任务有所减少。" #: ../../reference/import.rst:247 msgid "Import hooks" msgstr "导入钩子" #: ../../reference/import.rst:257 msgid "" "The import machinery is designed to be extensible; the primary mechanism for" " this are the *import hooks*. There are two types of import hooks: *meta " "hooks* and *import path hooks*." msgstr "导入机制被设计为可扩展;其中的基本机制是 *导入钩子*。 导入钩子有两种类型: *元钩子* 和 *导入路径钩子*。" #: ../../reference/import.rst:261 msgid "" "Meta hooks are called at the start of import processing, before any other " "import processing has occurred, other than :data:`sys.modules` cache look " "up. This allows meta hooks to override :data:`sys.path` processing, frozen " "modules, or even built-in modules. Meta hooks are registered by adding new " "finder objects to :data:`sys.meta_path`, as described below." msgstr "" "元钩子在导入过程开始时被调用,此时任何其他导入过程尚未发生,但 :data:`sys.modules` 缓存查找除外。 这允许元钩子重载 " ":data:`sys.path` 过程、冻结模块甚至内置模块。 元钩子的注册是通过向 :data:`sys.meta_path` " "添加新的查找器对象,具体如下所述。" #: ../../reference/import.rst:267 msgid "" "Import path hooks are called as part of :data:`sys.path` (or " "``package.__path__``) processing, at the point where their associated path " "item is encountered. Import path hooks are registered by adding new " "callables to :data:`sys.path_hooks` as described below." msgstr "" "导入路径钩子是作为 :data:`sys.path` (或 ``package.__path__``) " "过程的一部分,在遇到它们所关联的路径项的时候被调用。 导入路径钩子的注册是通过向 :data:`sys.path_hooks` " "添加新的可调用对象,具体如下所述。" #: ../../reference/import.rst:274 msgid "The meta path" msgstr "元路径" #: ../../reference/import.rst:280 msgid "" "When the named module is not found in :data:`sys.modules`, Python next " "searches :data:`sys.meta_path`, which contains a list of meta path finder " "objects. These finders are queried in order to see if they know how to " "handle the named module. Meta path finders must implement a method called " ":meth:`~importlib.abc.MetaPathFinder.find_spec()` which takes three " "arguments: a name, an import path, and (optionally) a target module. The " "meta path finder can use any strategy it wants to determine whether it can " "handle the named module or not." msgstr "" "当指定名称的模块在 :data:`sys.modules` 中找不到时,Python 会接着搜索 " ":data:`sys.meta_path`,其中包含元路径查找器对象列表。 这些查找器按顺序被查询以确定它们是否知道如何处理该名称的模块。 " "元路径查找器必须实现名为 :meth:`~importlib.abc.MetaPathFinder.find_spec()` " "的方法,该方法接受三个参数:名称、导入路径和目标模块(可选)。 元路径查找器可使用任何策略来确定它是否能处理指定名称的模块。" #: ../../reference/import.rst:289 msgid "" "If the meta path finder knows how to handle the named module, it returns a " "spec object. If it cannot handle the named module, it returns ``None``. If" " :data:`sys.meta_path` processing reaches the end of its list without " "returning a spec, then a :exc:`ModuleNotFoundError` is raised. Any other " "exceptions raised are simply propagated up, aborting the import process." msgstr "" "如果元路径查找器知道如何处理指定名称的模块,它将返回一个说明对象。 如果它不能处理该名称的模块,则会返回 ``None``。 如果 " ":data:`sys.meta_path` 处理过程到达列表末尾仍未返回说明对象,则将引发 :exc:`ModuleNotFoundError`。 " "任何其他被引发异常将直接向上传播,并放弃导入过程。" #: ../../reference/import.rst:295 msgid "" "The :meth:`~importlib.abc.MetaPathFinder.find_spec()` method of meta path " "finders is called with two or three arguments. The first is the fully " "qualified name of the module being imported, for example ``foo.bar.baz``. " "The second argument is the path entries to use for the module search. For " "top-level modules, the second argument is ``None``, but for submodules or " "subpackages, the second argument is the value of the parent package's " "``__path__`` attribute. If the appropriate ``__path__`` attribute cannot be " "accessed, a :exc:`ModuleNotFoundError` is raised. The third argument is an " "existing module object that will be the target of loading later. The import " "system passes in a target module only during reload." msgstr "" "元路径查找器的 :meth:`~importlib.abc.MetaPathFinder.find_spec()` 方法调用带有两到三个参数。 " "第一个是被导入模块的完整限定名称,例如 ``foo.bar.baz``。 第二个参数是供模块搜索使用的路径条目。 对于最高层级模块,第二个参数为 " "``None``,但对于子模块或子包,第二个参数为父包 ``__path__`` 属性的值。 如果相应的 ``__path__`` 属性无法访问,将引发" " :exc:`ModuleNotFoundError`。 第三个参数是一个将被作为稍后加载目标的现有模块对象。 " "导入系统仅会在重加载期间传入一个目标模块。" #: ../../reference/import.rst:306 msgid "" "The meta path may be traversed multiple times for a single import request. " "For example, assuming none of the modules involved has already been cached, " "importing ``foo.bar.baz`` will first perform a top level import, calling " "``mpf.find_spec(\"foo\", None, None)`` on each meta path finder (``mpf``). " "After ``foo`` has been imported, ``foo.bar`` will be imported by traversing " "the meta path a second time, calling ``mpf.find_spec(\"foo.bar\", " "foo.__path__, None)``. Once ``foo.bar`` has been imported, the final " "traversal will call ``mpf.find_spec(\"foo.bar.baz\", foo.bar.__path__, " "None)``." msgstr "" "对于单个导入请求可以多次遍历元路径。 例如,假设所涉及的模块都尚未被缓存,则导入 ``foo.bar.baz`` " "将首先执行顶级的导入,在每个元路径查找器 (``mpf``) 上调用 ``mpf.find_spec(\"foo\", None, None)``。 " "在导入 ``foo`` 之后,``foo.bar`` 将通过第二次遍历元路径来导入,调用 ``mpf.find_spec(\"foo.bar\", " "foo.__path__, None)``。 一旦 ``foo.bar`` 完成导入,最后一次遍历将调用 " "``mpf.find_spec(\"foo.bar.baz\", foo.bar.__path__, None)``。" #: ../../reference/import.rst:316 msgid "" "Some meta path finders only support top level imports. These importers will " "always return ``None`` when anything other than ``None`` is passed as the " "second argument." msgstr "有些元路径查找器只支持顶级导入。 当把 ``None`` 以外的对象作为第三个参数传入时,这些导入器将总是返回 ``None``。" #: ../../reference/import.rst:320 msgid "" "Python's default :data:`sys.meta_path` has three meta path finders, one that" " knows how to import built-in modules, one that knows how to import frozen " "modules, and one that knows how to import modules from an :term:`import " "path` (i.e. the :term:`path based finder`)." msgstr "" "Python 的默认 :data:`sys.meta_path` " "具有三种元路径查找器,一种知道如何导入内置模块,一种知道如何导入冻结模块,还有一种知道如何导入来自 :term:`import path` 的模块 (即" " :term:`path based finder`)。" #: ../../reference/import.rst:325 msgid "" "The :meth:`~importlib.abc.MetaPathFinder.find_spec` method of meta path " "finders replaced :meth:`~importlib.abc.MetaPathFinder.find_module`, which is" " now deprecated. While it will continue to work without change, the import " "machinery will try it only if the finder does not implement " ":meth:`~importlib.abc.MetaPathFinder.find_spec`." msgstr "" #: ../../reference/import.rst:332 msgid "" "Use of :meth:`~importlib.abc.MetaPathFinder.find_module` by the import " "system now raises :exc:`ImportWarning`." msgstr "" "导入系统使用 :meth:`~importlib.abc.MetaPathFinder.find_module` 现在将会引发 " ":exc:`ImportWarning`。" #: ../../reference/import.rst:338 msgid "Loading" msgstr "加载" #: ../../reference/import.rst:340 msgid "" "If and when a module spec is found, the import machinery will use it (and " "the loader it contains) when loading the module. Here is an approximation " "of what happens during the loading portion of import::" msgstr "当一个模块说明被找到时,导入机制将在加载该模块时使用它(及其所包含的加载器)。 下面是导入的加载部分所发生过程的简要说明::" #: ../../reference/import.rst:374 msgid "Note the following details:" msgstr "请注意以下细节:" #: ../../reference/import.rst:376 msgid "" "If there is an existing module object with the given name in " ":data:`sys.modules`, import will have already returned it." msgstr "如果在 :data:`sys.modules` 中存在指定名称的模块对象,导入操作会已经将其返回。" #: ../../reference/import.rst:379 msgid "" "The module will exist in :data:`sys.modules` before the loader executes the " "module code. This is crucial because the module code may (directly or " "indirectly) import itself; adding it to :data:`sys.modules` beforehand " "prevents unbounded recursion in the worst case and multiple loading in the " "best." msgstr "" "在加载器执行模块代码之前,该模块将存在于 :data:`sys.modules` 中。 " "这一点很关键,因为该模块代码可能(直接或间接地)导入其自身;预先将其添加到 :data:`sys.modules` " "可防止在最坏情况下的无限递归和最好情况下的多次加载。" #: ../../reference/import.rst:385 msgid "" "If loading fails, the failing module -- and only the failing module -- gets " "removed from :data:`sys.modules`. Any module already in the " ":data:`sys.modules` cache, and any module that was successfully loaded as a " "side-effect, must remain in the cache. This contrasts with reloading where " "even the failing module is left in :data:`sys.modules`." msgstr "" "如果加载失败,则该模块 -- 只限加载失败的模块 -- 将从 :data:`sys.modules` 中移除。 任何已存在于 " ":data:`sys.modules` 缓存的模块,以及任何作为附带影响被成功加载的模块仍会保留在缓存中。 " "这与重新加载不同,后者会把即使加载失败的模块也保留在 :data:`sys.modules` 中。" #: ../../reference/import.rst:391 msgid "" "After the module is created but before execution, the import machinery sets " "the import-related module attributes (\"_init_module_attrs\" in the pseudo-" "code example above), as summarized in a :ref:`later section `." msgstr "" "在模块创建完成但还未执行之前,导入机制会设置导入相关模块属性(在上面的示例伪代码中为 “_init_module_attrs”),详情参见 " ":ref:`后续部分 `。" #: ../../reference/import.rst:396 msgid "" "Module execution is the key moment of loading in which the module's " "namespace gets populated. Execution is entirely delegated to the loader, " "which gets to decide what gets populated and how." msgstr "模块执行是加载的关键时刻,在此期间将填充模块的命名空间。 执行会完全委托给加载器,由加载器决定要填充的内容和方式。" #: ../../reference/import.rst:400 msgid "" "The module created during loading and passed to exec_module() may not be the" " one returned at the end of import [#fnlo]_." msgstr "在加载过程中创建并传递给 exec_module() 的模块并不一定就是在导入结束时返回的模块 [#fnlo]_。" #: ../../reference/import.rst:403 msgid "" "The import system has taken over the boilerplate responsibilities of " "loaders. These were previously performed by the " ":meth:`importlib.abc.Loader.load_module` method." msgstr "" "导入系统已经接管了加载器建立样板的责任。 这些在以前是由 :meth:`importlib.abc.Loader.load_module` " "方法来执行的。" #: ../../reference/import.rst:409 msgid "Loaders" msgstr "加载器" #: ../../reference/import.rst:411 msgid "" "Module loaders provide the critical function of loading: module execution. " "The import machinery calls the :meth:`importlib.abc.Loader.exec_module` " "method with a single argument, the module object to execute. Any value " "returned from :meth:`~importlib.abc.Loader.exec_module` is ignored." msgstr "" "模块加载器提供关键的加载功能:模块执行。 导入机制调用 :meth:`importlib.abc.Loader.exec_module` " "方法并传入一个参数来执行模块对象。 从 :meth:`~importlib.abc.Loader.exec_module` 返回的任何值都将被忽略。" #: ../../reference/import.rst:416 msgid "Loaders must satisfy the following requirements:" msgstr "加载器必须满足下列要求:" #: ../../reference/import.rst:418 msgid "" "If the module is a Python module (as opposed to a built-in module or a " "dynamically loaded extension), the loader should execute the module's code " "in the module's global name space (``module.__dict__``)." msgstr "" "如果模块是一个 Python 模块(而非内置模块或动态加载的扩展),加载器应该在模块的全局命名空间 (``module.__dict__``) " "中执行模块的代码。" #: ../../reference/import.rst:422 msgid "" "If the loader cannot execute the module, it should raise an " ":exc:`ImportError`, although any other exception raised during " ":meth:`~importlib.abc.Loader.exec_module` will be propagated." msgstr "" "如果加载器无法执行指定模块,它应该引发 :exc:`ImportError`,不过在 " ":meth:`~importlib.abc.Loader.exec_module` 期间引发的任何其他异常也会被传播。" #: ../../reference/import.rst:426 msgid "" "In many cases, the finder and loader can be the same object; in such cases " "the :meth:`~importlib.abc.MetaPathFinder.find_spec` method would just return" " a spec with the loader set to ``self``." msgstr "" "在许多情况下,查找器和加载器可以是同一对象;在此情况下 :meth:`~importlib.abc.MetaPathFinder.find_spec` " "方法将返回一个规格说明,其中加载器会被设为 ``self``。" #: ../../reference/import.rst:430 msgid "" "Module loaders may opt in to creating the module object during loading by " "implementing a :meth:`~importlib.abc.Loader.create_module` method. It takes " "one argument, the module spec, and returns the new module object to use " "during loading. ``create_module()`` does not need to set any attributes on " "the module object. If the method returns ``None``, the import machinery " "will create the new module itself." msgstr "" "模块加载器可以选择通过实现 :meth:`~importlib.abc.Loader.create_module` 方法在加载期间创建模块对象。 " "它接受一个参数,即模块规格说明,并返回新的模块对象供加载期间使用。 ``create_module()`` 不需要在模块对象上设置任何属性。 " "如果模块返回 ``None``,导入机制将自行创建新模块。" #: ../../reference/import.rst:437 msgid "The :meth:`~importlib.abc.Loader.create_module` method of loaders." msgstr "加载器的 :meth:`~importlib.abc.Loader.create_module` 方法。" #: ../../reference/import.rst:440 msgid "" "The :meth:`~importlib.abc.Loader.load_module` method was replaced by " ":meth:`~importlib.abc.Loader.exec_module` and the import machinery assumed " "all the boilerplate responsibilities of loading." msgstr "" ":meth:`~importlib.abc.Loader.load_module` 方法被 " ":meth:`~importlib.abc.Loader.exec_module` 所替代,导入机制会对加载的所有样板责任作出假定。" #: ../../reference/import.rst:445 msgid "" "For compatibility with existing loaders, the import machinery will use the " "``load_module()`` method of loaders if it exists and the loader does not " "also implement ``exec_module()``. However, ``load_module()`` has been " "deprecated and loaders should implement ``exec_module()`` instead." msgstr "" "为了与现有的加载器兼容,导入机制会使用导入器的 ``load_module()`` 方法,如果它存在且导入器也未实现 " "``exec_module()``。 但是,``load_module()`` 现已弃用,加载器应该转而实现 ``exec_module()``。" #: ../../reference/import.rst:450 msgid "" "The ``load_module()`` method must implement all the boilerplate loading " "functionality described above in addition to executing the module. All the " "same constraints apply, with some additional clarification:" msgstr "" "除了执行模块之外,``load_module()`` 方法必须实现上文描述的所有样板加载功能。 所有相同的限制仍然适用,并带有一些附加规定:" #: ../../reference/import.rst:454 msgid "" "If there is an existing module object with the given name in " ":data:`sys.modules`, the loader must use that existing module. (Otherwise, " ":func:`importlib.reload` will not work correctly.) If the named module does" " not exist in :data:`sys.modules`, the loader must create a new module " "object and add it to :data:`sys.modules`." msgstr "" "如果 :data:`sys.modules` 中存在指定名称的模块对象,加载器必须使用已存在的模块。 (否则 " ":func:`importlib.reload` 将无法正确工作。) 如果该名称模块不存在于 :data:`sys.modules` " "中,加载器必须创建一个新的模块对象并将其加入 :data:`sys.modules`。" #: ../../reference/import.rst:460 msgid "" "The module *must* exist in :data:`sys.modules` before the loader executes " "the module code, to prevent unbounded recursion or multiple loading." msgstr "在加载器执行模块代码之前,模块 *必须* 存在于 :data:`sys.modules` 之中,以防止无限递归或多次加载。" #: ../../reference/import.rst:464 msgid "" "If loading fails, the loader must remove any modules it has inserted into " ":data:`sys.modules`, but it must remove **only** the failing module(s), and " "only if the loader itself has loaded the module(s) explicitly." msgstr "" "如果加载失败,加载器必须移除任何它已加入到 :data:`sys.modules` 中的模块,但它必须 **仅限** " "移除加载失败的模块,且所移除的模块应为加载器自身显式加载的。" #: ../../reference/import.rst:469 msgid "" "A :exc:`DeprecationWarning` is raised when ``exec_module()`` is defined but " "``create_module()`` is not." msgstr "" "当 ``exec_module()`` 已定义但 ``create_module()`` 未定义时将引发 " ":exc:`DeprecationWarning`。" #: ../../reference/import.rst:473 msgid "" "An :exc:`ImportError` is raised when ``exec_module()`` is defined but " "``create_module()`` is not." msgstr "" "当 ``exec_module()`` 已定义但 ``create_module()`` 未定义时将引发 :exc:`ImportError`。" #: ../../reference/import.rst:477 msgid "Use of ``load_module()`` will raise :exc:`ImportWarning`." msgstr "使用 ``load_module()`` 将引发 :exc:`ImportWarning`。" #: ../../reference/import.rst:481 msgid "Submodules" msgstr "子模块" #: ../../reference/import.rst:483 msgid "" "When a submodule is loaded using any mechanism (e.g. ``importlib`` APIs, the" " ``import`` or ``import-from`` statements, or built-in ``__import__()``) a " "binding is placed in the parent module's namespace to the submodule object. " "For example, if package ``spam`` has a submodule ``foo``, after importing " "``spam.foo``, ``spam`` will have an attribute ``foo`` which is bound to the " "submodule. Let's say you have the following directory structure::" msgstr "" "当使用任意机制 (例如 ``importlib`` API, ``import`` 及 ``import-from`` 语句或者内置的 " "``__import__()``) 加载一个子模块时,父模块的命名空间中会添加一个对子模块对象的绑定。 例如,如果包 ``spam`` 有一个子模块 " "``foo``,则在导入 ``spam.foo`` 之后,``spam`` 将具有一个 绑定到相应子模块的 ``foo`` 属性。 " "假如现在有如下的目录结构::" #: ../../reference/import.rst:494 msgid "and ``spam/__init__.py`` has the following line in it::" msgstr "并且 ``spam/__init__.py`` 中有如下几行内容::" #: ../../reference/import.rst:498 msgid "" "then executing the following puts name bindings for ``foo`` and ``Foo`` in " "the ``spam`` module::" msgstr "那么执行如下代码将把 ``foo`` 和 ``Foo`` 的名称绑定添加到 ``spam`` 模块中::" #: ../../reference/import.rst:507 msgid "" "Given Python's familiar name binding rules this might seem surprising, but " "it's actually a fundamental feature of the import system. The invariant " "holding is that if you have ``sys.modules['spam']`` and " "``sys.modules['spam.foo']`` (as you would after the above import), the " "latter must appear as the ``foo`` attribute of the former." msgstr "" "按照通常的 Python 名称绑定规则,这看起来可能会令人惊讶,但它实际上是导入系统的一个基本特性。 保持不变的一点是如果你有 " "``sys.modules['spam']`` 和 ``sys.modules['spam.foo']`` " "(例如在上述导入之后就是如此),则后者必须显示为前者的 ``foo`` 属性。" #: ../../reference/import.rst:514 msgid "Module spec" msgstr "模块规格说明" #: ../../reference/import.rst:516 msgid "" "The import machinery uses a variety of information about each module during " "import, especially before loading. Most of the information is common to all" " modules. The purpose of a module's spec is to encapsulate this import-" "related information on a per-module basis." msgstr "" "导入机制在导入期间会使用有关每个模块的多种信息,特别是加载之前。 大多数信息都是所有模块通用的。 " "模块规格说明的目的是基于每个模块来封装这些导入相关信息。" #: ../../reference/import.rst:521 msgid "" "Using a spec during import allows state to be transferred between import " "system components, e.g. between the finder that creates the module spec and " "the loader that executes it. Most importantly, it allows the import " "machinery to perform the boilerplate operations of loading, whereas without " "a module spec the loader had that responsibility." msgstr "" "在导入期间使用规格说明可允许状态在导入系统各组件之间传递,例如在创建模块规格说明的查找器和执行模块的加载器之间。 " "最重要的一点是,它允许导入机制执行加载的样板操作,在没有模块规格说明的情况下这是加载器的责任。" #: ../../reference/import.rst:527 msgid "" "The module's spec is exposed as the ``__spec__`` attribute on a module " "object. See :class:`~importlib.machinery.ModuleSpec` for details on the " "contents of the module spec." msgstr "" "模块的规格说明会作为模块对象的 ``__spec__`` 属性对外公开。 有关模块规格的详细内容请参阅 " ":class:`~importlib.machinery.ModuleSpec`。" #: ../../reference/import.rst:536 msgid "Import-related module attributes" msgstr "导入相关的模块属性" #: ../../reference/import.rst:538 msgid "" "The import machinery fills in these attributes on each module object during " "loading, based on the module's spec, before the loader executes the module." msgstr "导入机制会在加载期间会根据模块的规格说明填充每个模块对象的这些属性,并在加载器执行模块之前完成。" #: ../../reference/import.rst:544 msgid "" "The ``__name__`` attribute must be set to the fully qualified name of the " "module. This name is used to uniquely identify the module in the import " "system." msgstr "``__name__`` 属性必须被设为模块的完整限定名称。 此名称被用来在导入系统中唯一地标识模块。" #: ../../reference/import.rst:550 msgid "" "The ``__loader__`` attribute must be set to the loader object that the " "import machinery used when loading the module. This is mostly for " "introspection, but can be used for additional loader-specific functionality," " for example getting data associated with a loader." msgstr "" "``__loader__`` 属性必须被设为导入系统在加载模块时使用的加载器对象。 " "这主要是用于内省,但也可用于额外的加载器专用功能,例如获取关联到加载器的数据。" #: ../../reference/import.rst:557 msgid "" "The module's ``__package__`` attribute must be set. Its value must be a " "string, but it can be the same value as its ``__name__``. When the module " "is a package, its ``__package__`` value should be set to its ``__name__``. " "When the module is not a package, ``__package__`` should be set to the empty" " string for top-level modules, or for submodules, to the parent package's " "name. See :pep:`366` for further details." msgstr "" "模块的 ``__package__`` 属性必须设定。 其取值必须为一个字符串,但可以与 ``__name__`` 取相同的值。 当模块是包时,其 " "``__package__`` 值应该设为其 ``__name__`` 值。 当模块不是包时,对于最高层级模块 ``__package__`` " "应该设为空字符串,对于子模块则应该设为其父包名。 更多详情可参阅 :pep:`366`。" #: ../../reference/import.rst:565 msgid "" "This attribute is used instead of ``__name__`` to calculate explicit " "relative imports for main modules, as defined in :pep:`366`. It is expected " "to have the same value as ``__spec__.parent``." msgstr "" "该属性取代 ``__name__`` 被用来为主模块计算显式相对导入,相关定义见 :pep:`366`。 预期它与 " "``__spec__.parent`` 具有相同的值。" #: ../../reference/import.rst:569 msgid "" "The value of ``__package__`` is expected to be the same as " "``__spec__.parent``." msgstr "``__package__`` 预期与 ``__spec__.parent`` 具有相同的值。" #: ../../reference/import.rst:575 msgid "" "The ``__spec__`` attribute must be set to the module spec that was used when" " importing the module. Setting ``__spec__`` appropriately applies equally to" " :ref:`modules initialized during interpreter startup `. The one " "exception is ``__main__``, where ``__spec__`` is :ref:`set to None in some " "cases `." msgstr "" "``__spec__`` 属性必须设为在导入模块时要使用的模块规格说明。 对 ``__spec__`` 的正确设定将同时作用于 " ":ref:`解释器启动期间初始化的模块 `。 唯一的例外是 ``__main__``,其中的 ``__spec__`` 会 " ":ref:`在某些情况下设为 None `." #: ../../reference/import.rst:581 msgid "" "When ``__package__`` is not defined, ``__spec__.parent`` is used as a " "fallback." msgstr "当 ``__package__`` 未定义时, ``__spec__.parent`` 会被用作回退项。" #: ../../reference/import.rst:586 msgid "" "``__spec__.parent`` is used as a fallback when ``__package__`` is not " "defined." msgstr "当 ``__package__`` 未定义时,``__spec__.parent`` 会被用作回退项。" #: ../../reference/import.rst:592 msgid "" "If the module is a package (either regular or namespace), the module " "object's ``__path__`` attribute must be set. The value must be iterable, " "but may be empty if ``__path__`` has no further significance. If " "``__path__`` is not empty, it must produce strings when iterated over. More " "details on the semantics of ``__path__`` are given :ref:`below `." msgstr "" "如果模块为包(不论是正规包还是命名空间包),则必须设置模块对象的 ``__path__`` 属性。 属性值必须为可迭代对象,但如果 " "``__path__`` 没有进一步的用处则可以为空。 如果 ``__path__`` 不为空,则在迭代时它应该产生字符串。 有关 " "``__path__`` 语义的更多细节将在 :ref:`下文 ` 中给出。" #: ../../reference/import.rst:599 msgid "Non-package modules should not have a ``__path__`` attribute." msgstr "不是包的模块不应该具有 ``__path__`` 属性。" #: ../../reference/import.rst:604 msgid "" "``__file__`` is optional (if set, value must be a string). It indicates the " "pathname of the file from which the module was loaded (if loaded from a " "file), or the pathname of the shared library file for extension modules " "loaded dynamically from a shared library. It might be missing for certain " "types of modules, such as C modules that are statically linked into the " "interpreter, and the import system may opt to leave it unset if it has no " "semantic meaning (e.g. a module loaded from a database)." msgstr "" "``__file__`` 是可选项(如果设置,其值必须为字符串)。 " "它指明要载入的模块所在文件的路径(如果是从文件载入),或者对于从共享库动态载入的扩展模块来说则是共享库文件的路径。 " "它对特定类型的模块来说可能是缺失的,例如静态链接到解释器中的 C 模块,并且导入系统也可能会在它没有语法意义时选择不设置它(例如是从数据库导入的模块)。" #: ../../reference/import.rst:613 msgid "" "If ``__file__`` is set then the ``__cached__`` attribute might also be set," " which is the path to any compiled version of the code (e.g. byte-compiled " "file). The file does not need to exist to set this attribute; the path can " "simply point to where the compiled file would exist (see :pep:`3147`)." msgstr "" "如果设置了 ``__file__`` 则 ``__cached__`` 属性也可能会被设置,它是指向任何代码的已编译版本的路径(即字节码文件)。 " "设置此属性并不需要存在相应的文件;该路径可以简单地指向已编译文件将要存在的位置 (参见 :pep:`3147`)。" #: ../../reference/import.rst:619 msgid "" "Note that ``__cached__`` may be set even if ``__file__`` is not set. " "However, that scenario is quite atypical. Ultimately, the loader is what " "makes use of the module spec provided by the finder (from which ``__file__``" " and ``__cached__`` are derived). So if a loader can load from a cached " "module but otherwise does not load from a file, that atypical scenario may " "be appropriate." msgstr "" "请注意 ``__cached__`` 即使在未设置 ``__file__`` 时也可能会被设置。 但是,那样的场景是非典型的。 最终,加载器会是查找器 " "(``__file__`` 和 ``__cached__`` 也是自它派生的) 所提供的模块规格说明的使用方。 " "因此如果一个加载器可以从缓存加载模块但是不能从文件加载,那样的非典型场景就是适当的。" #: ../../reference/import.rst:629 msgid "module.__path__" msgstr "module.__path__" #: ../../reference/import.rst:631 msgid "" "By definition, if a module has a ``__path__`` attribute, it is a package." msgstr "根据定义,如果一个模块具有 ``__path__`` 属性,它就是包。" #: ../../reference/import.rst:633 msgid "" "A package's ``__path__`` attribute is used during imports of its " "subpackages. Within the import machinery, it functions much the same as " ":data:`sys.path`, i.e. providing a list of locations to search for modules " "during import. However, ``__path__`` is typically much more constrained than" " :data:`sys.path`." msgstr "" "包的 ``__path__`` 属性会在导入其子包期间被使用。 在导入机制内部,它的功能与 :data:`sys.path` " "基本相同,即在导入期间提供一个模块搜索位置列表。 但是,``__path__`` 通常会比 :data:`sys.path` 受到更多限制。" #: ../../reference/import.rst:639 msgid "" "``__path__`` must be an iterable of strings, but it may be empty. The same " "rules used for :data:`sys.path` also apply to a package's ``__path__``, and " ":data:`sys.path_hooks` (described below) are consulted when traversing a " "package's ``__path__``." msgstr "" "``__path__`` 必须是由字符串组成的可迭代对象,但它也可以为空。 作用于 :data:`sys.path` 的规则同样适用于包的 " "``__path__``,并且 :data:`sys.path_hooks` (见下文) 会在遍历包的 ``__path__`` 时被查询。" #: ../../reference/import.rst:644 msgid "" "A package's ``__init__.py`` file may set or alter the package's ``__path__``" " attribute, and this was typically the way namespace packages were " "implemented prior to :pep:`420`. With the adoption of :pep:`420`, namespace" " packages no longer need to supply ``__init__.py`` files containing only " "``__path__`` manipulation code; the import machinery automatically sets " "``__path__`` correctly for the namespace package." msgstr "" "包的 ``__init__.py`` 文件可以设置或更改包的 ``__path__`` 属性,而且这是在 :pep:`420` " "之前实现命名空间包的典型方式。 随着 :pep:`420` 的引入,命名空间包不再需要提供仅包含 ``__path__`` 操控代码的 " "``__init__.py`` 文件;导入机制会自动为命名空间包正确地设置 ``__path__``。" #: ../../reference/import.rst:652 msgid "Module reprs" msgstr "模块的 repr" #: ../../reference/import.rst:654 msgid "" "By default, all modules have a usable repr, however depending on the " "attributes set above, and in the module's spec, you can more explicitly " "control the repr of module objects." msgstr "默认情况下,全部模块都具有一个可用的 repr,但是你可以依据上述的属性设置,在模块的规格说明中更为显式地控制模块对象的 repr。" #: ../../reference/import.rst:658 msgid "" "If the module has a spec (``__spec__``), the import machinery will try to " "generate a repr from it. If that fails or there is no spec, the import " "system will craft a default repr using whatever information is available on " "the module. It will try to use the ``module.__name__``, " "``module.__file__``, and ``module.__loader__`` as input into the repr, with " "defaults for whatever information is missing." msgstr "" "如果模块具有 spec (``__spec__``),导入机制将尝试用它来生成一个 repr。 如果生成失败或找不到 " "spec,导入系统将使用模块中的各种可用信息来制作一个默认 repr。 它将尝试使用 ``module.__name__``, " "``module.__file__`` 以及 ``module.__loader__`` 作为 repr 的输入,并将任何丢失的信息赋为默认值。" #: ../../reference/import.rst:665 msgid "Here are the exact rules used:" msgstr "以下是所使用的确切规则:" #: ../../reference/import.rst:667 msgid "" "If the module has a ``__spec__`` attribute, the information in the spec is " "used to generate the repr. The \"name\", \"loader\", \"origin\", and " "\"has_location\" attributes are consulted." msgstr "" "如果模块具有 ``__spec__`` 属性,其中的规格信息会被用来生成 repr。 被查询的属性有 \"name\", \"loader\", " "\"origin\" 和 \"has_location\" 等等。" #: ../../reference/import.rst:671 msgid "" "If the module has a ``__file__`` attribute, this is used as part of the " "module's repr." msgstr "如果模块具有 ``__file__`` 属性,这会被用作模块 repr 的一部分。" #: ../../reference/import.rst:674 msgid "" "If the module has no ``__file__`` but does have a ``__loader__`` that is not" " ``None``, then the loader's repr is used as part of the module's repr." msgstr "" "如果模块没有 ``__file__`` 但是有 ``__loader__`` 且取值不为 ``None``,则加载器的 repr 会被用作模块 repr" " 的一部分。" #: ../../reference/import.rst:677 msgid "Otherwise, just use the module's ``__name__`` in the repr." msgstr "对于其他情况,仅在 repr 中使用模块的 ``__name__``。" #: ../../reference/import.rst:679 msgid "" "Use of :meth:`loader.module_repr() ` has " "been deprecated and the module spec is now used by the import machinery to " "generate a module repr." msgstr "" ":meth:`loader.module_repr() ` " "已弃用,导入机制现在使用模块规格说明来生成模块 repr。" #: ../../reference/import.rst:684 msgid "" "For backward compatibility with Python 3.3, the module repr will be " "generated by calling the loader's :meth:`~importlib.abc.Loader.module_repr` " "method, if defined, before trying either approach described above. However," " the method is deprecated." msgstr "" "为了向后兼容 Python 3.3,如果加载器定义了 :meth:`~importlib.abc.Loader.module_repr` " "方法,则会在尝试上述两种方式之前先调用该方法来生成模块 repr。 但请注意此方法已弃用。" #: ../../reference/import.rst:691 msgid "" "Calling :meth:`~importlib.abc.Loader.module_repr` now occurs after trying to" " use a module's ``__spec__`` attribute but before falling back on " "``__file__``. Use of :meth:`~importlib.abc.Loader.module_repr` is slated to " "stop in Python 3.12." msgstr "" "对 :meth:`~importlib.abc.Loader.module_repr` 的调用现在会在尝试使用模块的 ``__spec__`` " "属性之后但在回退至 ``__file__`` 之前发生。 :meth:`~importlib.abc.Loader.module_repr` " "的使用预定会在 Python 3.12 中停止。" #: ../../reference/import.rst:699 msgid "Cached bytecode invalidation" msgstr "已缓存字节码的失效" #: ../../reference/import.rst:701 msgid "" "Before Python loads cached bytecode from a ``.pyc`` file, it checks whether " "the cache is up-to-date with the source ``.py`` file. By default, Python " "does this by storing the source's last-modified timestamp and size in the " "cache file when writing it. At runtime, the import system then validates the" " cache file by checking the stored metadata in the cache file against the " "source's metadata." msgstr "" "在 Python 从 ``.pyc`` 文件加载已缓存字节码之前,它会检查缓存是否由最新的 ``.py`` 源文件所生成。 默认情况下,Python " "通过在所写入缓存文件中保存源文件的最新修改时间戳和大小来实现这一点。 " "在运行时,导入系统会通过比对缓存文件中保存的元数据和源文件的元数据确定该缓存的有效性。" #: ../../reference/import.rst:708 msgid "" "Python also supports \"hash-based\" cache files, which store a hash of the " "source file's contents rather than its metadata. There are two variants of " "hash-based ``.pyc`` files: checked and unchecked. For checked hash-based " "``.pyc`` files, Python validates the cache file by hashing the source file " "and comparing the resulting hash with the hash in the cache file. If a " "checked hash-based cache file is found to be invalid, Python regenerates it " "and writes a new checked hash-based cache file. For unchecked hash-based " "``.pyc`` files, Python simply assumes the cache file is valid if it exists. " "Hash-based ``.pyc`` files validation behavior may be overridden with the " ":option:`--check-hash-based-pycs` flag." msgstr "" "Python 也支持“基于哈希的”缓存文件,即保存源文件内容的哈希值而不是其元数据。 存在两种基于哈希的 ``.pyc`` 文件:检查型和非检查型。 " "对于检查型基于哈希的 ``.pyc`` 文件,Python 会通过求哈希源文件并将结果哈希值与缓存文件中的哈希值比对来确定缓存有效性。 " "如果检查型基于哈希的缓存文件被确定为失效,Python 会重新生成并写入一个新的检查型基于哈希的缓存文件。 对于非检查型 ``.pyc`` " "文件,只要其存在 Python 就会直接认定缓存文件有效。 确定基于哈希的 ``.pyc`` 文件有效性的行为可通过 :option:`--check-" "hash-based-pycs` 旗标来重载。" #: ../../reference/import.rst:719 msgid "" "Added hash-based ``.pyc`` files. Previously, Python only supported " "timestamp-based invalidation of bytecode caches." msgstr "增加了基于哈希的 ``.pyc`` 文件。在此之前,Python 只支持基于时间戳来确定字节码缓存的有效性。" #: ../../reference/import.rst:725 msgid "The Path Based Finder" msgstr "基于路径的查找器" #: ../../reference/import.rst:730 msgid "" "As mentioned previously, Python comes with several default meta path " "finders. One of these, called the :term:`path based finder` " "(:class:`~importlib.machinery.PathFinder`), searches an :term:`import path`," " which contains a list of :term:`path entries `. Each path " "entry names a location to search for modules." msgstr "" "在之前已经提及,Python 带有几种默认的元路径查找器。 其中之一是 :term:`path based finder` " "(:class:`~importlib.machinery.PathFinder`),它会搜索包含一个 :term:`路径条目 ` 列表的 :term:`import path`。 每个路径条目指定一个用于搜索模块的位置。" #: ../../reference/import.rst:736 msgid "" "The path based finder itself doesn't know how to import anything. Instead, " "it traverses the individual path entries, associating each of them with a " "path entry finder that knows how to handle that particular kind of path." msgstr "基于路径的查找器自身并不知道如何进行导入。 它只是遍历单独的路径条目,将它们各自关联到某个知道如何处理特定类型路径的路径条目查找器。" #: ../../reference/import.rst:740 msgid "" "The default set of path entry finders implement all the semantics for " "finding modules on the file system, handling special file types such as " "Python source code (``.py`` files), Python byte code (``.pyc`` files) and " "shared libraries (e.g. ``.so`` files). When supported by the " ":mod:`zipimport` module in the standard library, the default path entry " "finders also handle loading all of these file types (other than shared " "libraries) from zipfiles." msgstr "" "默认的路径条目查找器集合实现了在文件系统中查找模块的所有语义,可处理多种特殊文件类型例如 Python 源码 (``.py`` 文件),Python " "字节码 (``.pyc`` 文件) 以及共享库 (例如 ``.so`` 文件)。 在标准库中 :mod:`zipimport` " "模块的支持下,默认路径条目查找器还能处理所有来自 zip 文件的上述文件类型。" #: ../../reference/import.rst:747 msgid "" "Path entries need not be limited to file system locations. They can refer " "to URLs, database queries, or any other location that can be specified as a " "string." msgstr "路径条目不必仅限于文件系统位置。 它们可以指向 URL、数据库查询或可以用字符串指定的任何其他位置。" #: ../../reference/import.rst:751 msgid "" "The path based finder provides additional hooks and protocols so that you " "can extend and customize the types of searchable path entries. For example," " if you wanted to support path entries as network URLs, you could write a " "hook that implements HTTP semantics to find modules on the web. This hook " "(a callable) would return a :term:`path entry finder` supporting the " "protocol described below, which was then used to get a loader for the module" " from the web." msgstr "" "基于路径的查找器还提供了额外的钩子和协议以便能扩展和定制可搜索路径条目的类型。 例如,如果你想要支持网络 URL 形式的路径条目,你可以编写一个实现 " "HTTP 语义在网络上查找模块的钩子。 这个钩子(可调用对象)应当返回一个支持下述协议的 :term:`path entry " "finder`,以被用来获取一个专门针对来自网络的模块的加载器。" #: ../../reference/import.rst:759 msgid "" "A word of warning: this section and the previous both use the term *finder*," " distinguishing between them by using the terms :term:`meta path finder` and" " :term:`path entry finder`. These two types of finders are very similar, " "support similar protocols, and function in similar ways during the import " "process, but it's important to keep in mind that they are subtly different. " "In particular, meta path finders operate at the beginning of the import " "process, as keyed off the :data:`sys.meta_path` traversal." msgstr "" "预先的警告:本节和上节都使用了 *查找器* 这一术语,并通过 :term:`meta path finder` 和 :term:`path entry " "finder` 两个术语来明确区分它们。 " "这两种类型的查找器非常相似,支持相似的协议,且在导入过程中以相似的方式运作,但关键的一点是要记住它们是有微妙差异的。 " "特别地,元路径查找器作用于导入过程的开始,主要是启动 :data:`sys.meta_path` 遍历。" #: ../../reference/import.rst:767 msgid "" "By contrast, path entry finders are in a sense an implementation detail of " "the path based finder, and in fact, if the path based finder were to be " "removed from :data:`sys.meta_path`, none of the path entry finder semantics " "would be invoked." msgstr "" "相比之下,路径条目查找器在某种意义上说是基于路径的查找器的实现细节,实际上,如果需要从 :data:`sys.meta_path` " "移除基于路径的查找器,并不会有任何路径条目查找器被唤起。" #: ../../reference/import.rst:774 msgid "Path entry finders" msgstr "路径条目查找器" #: ../../reference/import.rst:782 msgid "" "The :term:`path based finder` is responsible for finding and loading Python " "modules and packages whose location is specified with a string :term:`path " "entry`. Most path entries name locations in the file system, but they need " "not be limited to this." msgstr "" ":term:`path based finder` 会负责查找和加载通过 :term:`path entry` 字符串来指定位置的 Python " "模块和包。 多数路径条目所指定的是文件系统中的位置,但它们并不必受限于此。" #: ../../reference/import.rst:787 msgid "" "As a meta path finder, the :term:`path based finder` implements the " ":meth:`~importlib.abc.MetaPathFinder.find_spec` protocol previously " "described, however it exposes additional hooks that can be used to customize" " how modules are found and loaded from the :term:`import path`." msgstr "" "作为一种元路径查找器,:term:`path based finder` 实现了上文描述的 " ":meth:`~importlib.abc.MetaPathFinder.find_spec` " "协议,但是它还对外公开了一些附加钩子,可被用来定制模块如何从 :term:`import path` 查找和加载。" #: ../../reference/import.rst:792 msgid "" "Three variables are used by the :term:`path based finder`, :data:`sys.path`," " :data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The " "``__path__`` attributes on package objects are also used. These provide " "additional ways that the import machinery can be customized." msgstr "" "有三个变量由 :term:`path based finder`, :data:`sys.path`, :data:`sys.path_hooks` 和" " :data:`sys.path_importer_cache` 所使用。 包对象的 ``__path__`` 属性也会被使用。 " "它们提供了可用于定制导入机制的额外方式。" #: ../../reference/import.rst:797 msgid "" ":data:`sys.path` contains a list of strings providing search locations for " "modules and packages. It is initialized from the :envvar:`PYTHONPATH` " "environment variable and various other installation- and implementation-" "specific defaults. Entries in :data:`sys.path` can name directories on the " "file system, zip files, and potentially other \"locations\" (see the " ":mod:`site` module) that should be searched for modules, such as URLs, or " "database queries. Only strings should be present on :data:`sys.path`; all " "other data types are ignored." msgstr "" ":data:`sys.path` 包含一个提供模块和包搜索位置的字符串列表。 它初始化自 :envvar:`PYTHONPATH` " "环境变量以及多种其他特定安装和实现专属的默认位置。 :data:`sys.path` 中的条目可指定文件系统中的目录、zip " "文件及其他可用于搜索模块的潜在“位置“(参见 :mod:`site` 模块),例如 URL 或数据库查询等。 在 :data:`sys.path` " "中应当只有字符串;所有其他数据类型都会被忽略。" #: ../../reference/import.rst:806 msgid "" "The :term:`path based finder` is a :term:`meta path finder`, so the import " "machinery begins the :term:`import path` search by calling the path based " "finder's :meth:`~importlib.machinery.PathFinder.find_spec` method as " "described previously. When the ``path`` argument to " ":meth:`~importlib.machinery.PathFinder.find_spec` is given, it will be a " "list of string paths to traverse - typically a package's ``__path__`` " "attribute for an import within that package. If the ``path`` argument is " "``None``, this indicates a top level import and :data:`sys.path` is used." msgstr "" ":term:`path based finder` 是一种 :term:`meta path " "finder`,因此导入机制会通过调用上文描述的基于路径的查找器的 " ":meth:`~importlib.machinery.PathFinder.find_spec` 方法来启动 :term:`import path` " "搜索。 当要向 :meth:`~importlib.machinery.PathFinder.find_spec` 传入 ``path`` " "参数时,它将是一个可遍历的字符串列表 —— 通常为用来在其内部进行导入的包的 ``__path__`` 属性。 如果 ``path`` 参数为 " "``None``,这表示最高层级的导入,将会使用 :data:`sys.path`。" #: ../../reference/import.rst:815 msgid "" "The path based finder iterates over every entry in the search path, and for " "each of these, looks for an appropriate :term:`path entry finder` " "(:class:`~importlib.abc.PathEntryFinder`) for the path entry. Because this " "can be an expensive operation (e.g. there may be ``stat()`` call overheads " "for this search), the path based finder maintains a cache mapping path " "entries to path entry finders. This cache is maintained in " ":data:`sys.path_importer_cache` (despite the name, this cache actually " "stores finder objects rather than being limited to :term:`importer` " "objects). In this way, the expensive search for a particular :term:`path " "entry` location's :term:`path entry finder` need only be done once. User " "code is free to remove cache entries from :data:`sys.path_importer_cache` " "forcing the path based finder to perform the path entry search again " "[#fnpic]_." msgstr "" "基于路径的查找器会迭代搜索路径中的每个条目,并且每次都查找与路径条目对应的 :term:`path entry finder` " "(:class:`~importlib.abc.PathEntryFinder`)。 因为这种操作可能很耗费资源 (例如搜索会有 ``stat()`` " "调用的开销),基于路径的查找器会维持一个缓存来将路径条目映射到路径条目查找器。 这个缓存存放在 " ":data:`sys.path_importer_cache` (尽管如此命名,但这个缓存实际存放的是查找器对象而非仅限于 " ":term:`importer` 对象)。 通过这种方式,对特定 :term:`path entry` 位置的 :term:`path entry " "finder` 的高耗费搜索中需要进行一次。 用户代码可以自由地从 :data:`sys.path_importer_cache` " "移除缓存条目,以强制基于路径的查找器再次执行路径条目搜索 [#fnpic]_。" #: ../../reference/import.rst:828 msgid "" "If the path entry is not present in the cache, the path based finder " "iterates over every callable in :data:`sys.path_hooks`. Each of the " ":term:`path entry hooks ` in this list is called with a " "single argument, the path entry to be searched. This callable may either " "return a :term:`path entry finder` that can handle the path entry, or it may" " raise :exc:`ImportError`. An :exc:`ImportError` is used by the path based " "finder to signal that the hook cannot find a :term:`path entry finder` for " "that :term:`path entry`. The exception is ignored and :term:`import path` " "iteration continues. The hook should expect either a string or bytes " "object; the encoding of bytes objects is up to the hook (e.g. it may be a " "file system encoding, UTF-8, or something else), and if the hook cannot " "decode the argument, it should raise :exc:`ImportError`." msgstr "" "如果路径条目不存在于缓存中,基于路径的查找器会迭代 :data:`sys.path_hooks` 中的每个可调用对象。 对此列表中的每个 " ":term:`路径条目钩子 ` 的调用会带有一个参数,即要搜索的路径条目。 每个可调用对象或是返回可处理路径条目的 " ":term:`path entry finder`,或是引发 :exc:`ImportError`。 基于路径的查找器使用 " ":exc:`ImportError` 来表示钩子无法找到与 :term:`path entry` 相对应的 :term:`path entry " "finder`。 该异常会被忽略并继续进行 :term:`import path` 的迭代。 " "每个钩子应该期待接收一个字符串或字节串对象;字节串对象的编码由钩子决定(例如可以是文件系统使用的编码 UTF-8 " "或其它编码),如果钩子无法解码参数,它应该引发 :exc:`ImportError`。" #: ../../reference/import.rst:842 msgid "" "If :data:`sys.path_hooks` iteration ends with no :term:`path entry finder` " "being returned, then the path based finder's " ":meth:`~importlib.machinery.PathFinder.find_spec` method will store ``None``" " in :data:`sys.path_importer_cache` (to indicate that there is no finder for" " this path entry) and return ``None``, indicating that this :term:`meta path" " finder` could not find the module." msgstr "" "如果 :data:`sys.path_hooks` 迭代结束时没有返回 :term:`path entry finder`,则基于路径的查找器 " ":meth:`~importlib.machinery.PathFinder.find_spec` 方法将在 " ":data:`sys.path_importer_cache` 中存入 ``None`` (表示此路径条目没有对应的查找器) 并返回 " "``None``,表示此 :term:`meta path finder` 无法找到该模块。" #: ../../reference/import.rst:849 msgid "" "If a :term:`path entry finder` *is* returned by one of the :term:`path entry" " hook` callables on :data:`sys.path_hooks`, then the following protocol is " "used to ask the finder for a module spec, which is then used when loading " "the module." msgstr "" "如果 :data:`sys.path_hooks` 中的某个 :term:`path entry hook` 可调用对象的返回值 *是* 一个 " ":term:`path entry finder`,则以下协议会被用来向查找器请求一个模块的规格说明,并在加载该模块时被使用。" #: ../../reference/import.rst:854 msgid "" "The current working directory -- denoted by an empty string -- is handled " "slightly differently from other entries on :data:`sys.path`. First, if the " "current working directory is found to not exist, no value is stored in " ":data:`sys.path_importer_cache`. Second, the value for the current working " "directory is looked up fresh for each module lookup. Third, the path used " "for :data:`sys.path_importer_cache` and returned by " ":meth:`importlib.machinery.PathFinder.find_spec` will be the actual current " "working directory and not the empty string." msgstr "" "当前工作目录 -- 由一个空字符串表示 -- 的处理方式与 :data:`sys.path` 中的其他条目略有不同。 " "首先,如果发现当前工作目录不存在,则 :data:`sys.path_importer_cache` 中不会存放任何值。 " "其次,每个模块查找会对当前工作目录的值进行全新查找。 第三,由 :data:`sys.path_importer_cache` 所使用并由 " ":meth:`importlib.machinery.PathFinder.find_spec` 所返回的路径将是实际的当前工作目录而非空字符串。" #: ../../reference/import.rst:864 msgid "Path entry finder protocol" msgstr "路径条目查找器协议" #: ../../reference/import.rst:866 msgid "" "In order to support imports of modules and initialized packages and also to " "contribute portions to namespace packages, path entry finders must implement" " the :meth:`~importlib.abc.PathEntryFinder.find_spec` method." msgstr "" "为了支持模块和已初始化包的导入,也为了给命名空间包提供组成部分,路径条目查找器必须实现 " ":meth:`~importlib.abc.PathEntryFinder.find_spec` 方法。" #: ../../reference/import.rst:870 msgid "" ":meth:`~importlib.abc.PathEntryFinder.find_spec` takes two arguments: the " "fully qualified name of the module being imported, and the (optional) target" " module. ``find_spec()`` returns a fully populated spec for the module. " "This spec will always have \"loader\" set (with one exception)." msgstr "" ":meth:`~importlib.abc.PathEntryFinder.find_spec` " "接受两个参数,即要导入模块的完整限定名称,以及(可选的)目标模块。 ``find_spec()`` 返回模块的完全填充好的规格说明。 " "这个规格说明总是包含“加载器”集合(但有一个例外)。" #: ../../reference/import.rst:875 msgid "" "To indicate to the import machinery that the spec represents a namespace " ":term:`portion`, the path entry finder sets \"submodule_search_locations\" " "to a list containing the portion." msgstr "" "为了向导入机制提示该规格说明代表一个命名空间 :term:`portion`,路径条目查找器会将 " "\"submodule_search_locations\" 设为一个包含该部分的列表。" #: ../../reference/import.rst:879 msgid "" ":meth:`~importlib.abc.PathEntryFinder.find_spec` replaced " ":meth:`~importlib.abc.PathEntryFinder.find_loader` and " ":meth:`~importlib.abc.PathEntryFinder.find_module`, both of which are now " "deprecated, but will be used if ``find_spec()`` is not defined." msgstr "" ":meth:`~importlib.abc.PathEntryFinder.find_spec` 替代了 " ":meth:`~importlib.abc.PathEntryFinder.find_loader` 和 " ":meth:`~importlib.abc.PathEntryFinder.find_module`,后两者现在都已弃用,但会在 " "``find_spec()`` 未定义时被使用。" #: ../../reference/import.rst:885 msgid "" "Older path entry finders may implement one of these two deprecated methods " "instead of ``find_spec()``. The methods are still respected for the sake of" " backward compatibility. However, if ``find_spec()`` is implemented on the " "path entry finder, the legacy methods are ignored." msgstr "" "较旧的路径条目查找器可能会实现这两个已弃用的方法中的一个而没有实现 ``find_spec()``。 为保持向后兼容,这两个方法仍会被接受。 " "但是,如果在路径条目查找器上实现了 ``find_spec()``,这两个遗留方法就会被忽略。" #: ../../reference/import.rst:890 msgid "" ":meth:`~importlib.abc.PathEntryFinder.find_loader` takes one argument, the " "fully qualified name of the module being imported. ``find_loader()`` " "returns a 2-tuple where the first item is the loader and the second item is " "a namespace :term:`portion`." msgstr "" ":meth:`~importlib.abc.PathEntryFinder.find_loader` 接受一个参数,即要导入模块的完整限定名称。 " "``find_loader()`` 返回一个 2 元组,其中第一项是加载器而第二项是命名空间 :term:`portion`。" #: ../../reference/import.rst:895 msgid "" "For backwards compatibility with other implementations of the import " "protocol, many path entry finders also support the same, traditional " "``find_module()`` method that meta path finders support. However path entry " "finder ``find_module()`` methods are never called with a ``path`` argument " "(they are expected to record the appropriate path information from the " "initial call to the path hook)." msgstr "" "为了向后兼容其他导入协议的实现,许多路径条目查找器也同样支持元路径查找器所支持的传统 ``find_module()`` 方法。 但是路径条目查找器 " "``find_module()`` 方法的调用绝不会带有 ``path`` 参数(它们被期望记录来自对路径钩子初始调用的恰当路径信息)。" #: ../../reference/import.rst:902 msgid "" "The ``find_module()`` method on path entry finders is deprecated, as it does" " not allow the path entry finder to contribute portions to namespace " "packages. If both ``find_loader()`` and ``find_module()`` exist on a path " "entry finder, the import system will always call ``find_loader()`` in " "preference to ``find_module()``." msgstr "" "路径条目查找器的 ``find_module()`` 方法已弃用,因为它不允许路径条目查找器为命名空间包提供部分。 如果 " "``find_loader()`` 和 ``find_module()`` 同时存在于一个路径条目查找器中,导入系统将总是调用 " "``find_loader()`` 而不选择 ``find_module()``。" #: ../../reference/import.rst:908 msgid "" "Calls to :meth:`~importlib.abc.PathEntryFinder.find_module` and " ":meth:`~importlib.abc.PathEntryFinder.find_loader` by the import system will" " raise :exc:`ImportWarning`." msgstr "" "导入系统调用 :meth:`~importlib.abc.PathEntryFinder.find_module` 和 " ":meth:`~importlib.abc.PathEntryFinder.find_loader` 将引发 :exc:`ImportWarning`。" #: ../../reference/import.rst:915 msgid "Replacing the standard import system" msgstr "替换标准导入系统" #: ../../reference/import.rst:917 msgid "" "The most reliable mechanism for replacing the entire import system is to " "delete the default contents of :data:`sys.meta_path`, replacing them " "entirely with a custom meta path hook." msgstr "替换整个导入系统的最可靠机制是移除 :data:`sys.meta_path` 的默认内容,,将其完全替换为自定义的元路径钩子。" #: ../../reference/import.rst:921 msgid "" "If it is acceptable to only alter the behaviour of import statements without" " affecting other APIs that access the import system, then replacing the " "builtin :func:`__import__` function may be sufficient. This technique may " "also be employed at the module level to only alter the behaviour of import " "statements within that module." msgstr "" "一个可行的方式是仅改变导入语句的行为而不影响访问导入系统的其他 API,那么替换内置的 :func:`__import__` 函数可能就够了。 " "这种技巧也可以在模块层级上运用,即只在某个模块内部改变导入语句的行为。" #: ../../reference/import.rst:927 msgid "" "To selectively prevent the import of some modules from a hook early on the " "meta path (rather than disabling the standard import system entirely), it is" " sufficient to raise :exc:`ModuleNotFoundError` directly from " ":meth:`~importlib.abc.MetaPathFinder.find_spec` instead of returning " "``None``. The latter indicates that the meta path search should continue, " "while raising an exception terminates it immediately." msgstr "" "想要选择性地预先防止在元路径上从一个钩子导入某些模块(而不是完全禁用标准导入系统),只需直接从 " ":meth:`~importlib.abc.MetaPathFinder.find_spec` 引发 " ":exc:`ModuleNotFoundError` 而非返回 ``None`` 就足够了。 " "返回后者表示元路径搜索应当继续,而引发异常则会立即终止搜索。" #: ../../reference/import.rst:937 msgid "Package Relative Imports" msgstr "包相对导入" #: ../../reference/import.rst:939 msgid "" "Relative imports use leading dots. A single leading dot indicates a relative" " import, starting with the current package. Two or more leading dots " "indicate a relative import to the parent(s) of the current package, one " "level per dot after the first. For example, given the following package " "layout::" msgstr "" "相对导入使用前缀点号。 一个前缀点号表示相对导入从当前包开始。 两个或更多前缀点号表示对当前包的上级包的相对导入,第一个点号之后的每个点号代表一级。 " "例如,给定以下的包布局结构::" #: ../../reference/import.rst:955 msgid "" "In either ``subpackage1/moduleX.py`` or ``subpackage1/__init__.py``, the " "following are valid relative imports::" msgstr "" "不论是在 ``subpackage1/moduleX.py`` 还是 ``subpackage1/__init__.py`` 中,以下导入都是有效的::" #: ../../reference/import.rst:965 msgid "" "Absolute imports may use either the ``import <>`` or ``from <> import <>`` " "syntax, but relative imports may only use the second form; the reason for " "this is that::" msgstr "" "绝对导入可以使用 ``import <>`` 或 ``from <> import <>`` 语法,但相对导入只能使用第二种形式;其中的原因在于::" #: ../../reference/import.rst:971 msgid "" "should expose ``XXX.YYY.ZZZ`` as a usable expression, but .moduleY is not a " "valid expression." msgstr "应当提供 ``XXX.YYY.ZZZ`` 作为可用表达式,但 .moduleY 不是一个有效的表达式。" #: ../../reference/import.rst:978 msgid "Special considerations for __main__" msgstr "有关 __main__ 的特殊事项" #: ../../reference/import.rst:980 msgid "" "The :mod:`__main__` module is a special case relative to Python's import " "system. As noted :ref:`elsewhere `, the ``__main__`` module is " "directly initialized at interpreter startup, much like :mod:`sys` and " ":mod:`builtins`. However, unlike those two, it doesn't strictly qualify as " "a built-in module. This is because the manner in which ``__main__`` is " "initialized depends on the flags and other options with which the " "interpreter is invoked." msgstr "" "对于 Python 的导入系统来说 :mod:`__main__` 模块是一个特殊情况。 正如在 :ref:`另一节 ` " "中所述,``__main__`` 模块是在解释器启动时直接初始化的,与 :mod:`sys` 和 :mod:`builtins` 很类似。 " "但是,与那两者不同,它并不被严格归类为内置模块。 这是因为 ``__main__`` 被初始化的方式依赖于唤起解释器所附带的旗标和其他选项。" #: ../../reference/import.rst:991 msgid "__main__.__spec__" msgstr "__main__.__spec__" #: ../../reference/import.rst:993 msgid "" "Depending on how :mod:`__main__` is initialized, ``__main__.__spec__`` gets " "set appropriately or to ``None``." msgstr "根据 :mod:`__main__` 被初始化的方式,``__main__.__spec__`` 会被设置相应值或是 ``None``。" #: ../../reference/import.rst:996 msgid "" "When Python is started with the :option:`-m` option, ``__spec__`` is set to " "the module spec of the corresponding module or package. ``__spec__`` is also" " populated when the ``__main__`` module is loaded as part of executing a " "directory, zipfile or other :data:`sys.path` entry." msgstr "" "当 Python 附加 :option:`-m` 选项启动时,``__spec__`` 会被设为相应模块或包的模块规格说明。 ``__spec__`` " "也会在 ``__main__`` 模块作为执行某个目录,zip 文件或其它 :data:`sys.path` 条目的一部分加载时被填充。" #: ../../reference/import.rst:1001 msgid "" "In :ref:`the remaining cases ` " "``__main__.__spec__`` is set to ``None``, as the code used to populate the " ":mod:`__main__` does not correspond directly with an importable module:" msgstr "" "在 :ref:`其余的情况 ` 下 ``__main__.__spec__`` 会被设为 " "``None``,因为用于填充 :mod:`__main__` 的代码不直接与可导入的模块相对应:" #: ../../reference/import.rst:1005 msgid "interactive prompt" msgstr "交互型提示" #: ../../reference/import.rst:1006 msgid ":option:`-c` option" msgstr ":option:`-c` 选项" #: ../../reference/import.rst:1007 msgid "running from stdin" msgstr "从 stdin 运行" #: ../../reference/import.rst:1008 msgid "running directly from a source or bytecode file" msgstr "直接从源码或字节码文件运行" #: ../../reference/import.rst:1010 msgid "" "Note that ``__main__.__spec__`` is always ``None`` in the last case, *even " "if* the file could technically be imported directly as a module instead. Use" " the :option:`-m` switch if valid module metadata is desired in " ":mod:`__main__`." msgstr "" "请注意在最后一种情况中 ``__main__.__spec__`` 总是为 ``None``,*即使* 文件从技术上说可以作为一个模块被导入。 " "如果想要让 :mod:`__main__` 中的元数据生效,请使用 :option:`-m` 开关。" #: ../../reference/import.rst:1015 msgid "" "Note also that even when ``__main__`` corresponds with an importable module " "and ``__main__.__spec__`` is set accordingly, they're still considered " "*distinct* modules. This is due to the fact that blocks guarded by ``if " "__name__ == \"__main__\":`` checks only execute when the module is used to " "populate the ``__main__`` namespace, and not during normal import." msgstr "" "还要注意即使是在 ``__main__`` 对应于一个可导入模块且 ``__main__.__spec__`` 被相应地设定时,它们仍会被视为 " "*不同的* 模块。 这是由于以下事实:使用 ``if __name__ == \"__main__\":`` 检测来保护的代码块仅会在模块被用来填充 " "``__main__`` 命名空间时而非普通的导入时被执行。" #: ../../reference/import.rst:1023 msgid "References" msgstr "参考文献" #: ../../reference/import.rst:1025 msgid "" "The import machinery has evolved considerably since Python's early days. " "The original `specification for packages " "`_ is still available to read, " "although some details have changed since the writing of that document." msgstr "" "导入机制自 Python 诞生之初至今已发生了很大的变化。 原始的 `包规格说明 " "`_ 仍然可以查阅,但在撰写该文档之后许多相关细节已被修改。" #: ../../reference/import.rst:1030 msgid "" "The original specification for :data:`sys.meta_path` was :pep:`302`, with " "subsequent extension in :pep:`420`." msgstr "原始的 :data:`sys.meta_path` 规格说明见 :pep:`302`,后续的扩展说明见 :pep:`420`。" #: ../../reference/import.rst:1033 msgid "" ":pep:`420` introduced :term:`namespace packages ` for " "Python 3.3. :pep:`420` also introduced the :meth:`find_loader` protocol as " "an alternative to :meth:`find_module`." msgstr "" ":pep:`420` 为 Python 3.3 引入了 :term:`命名空间包 `。 :pep:`420` " "还引入了 :meth:`find_loader` 协议作为 :meth:`find_module` 的替代。" #: ../../reference/import.rst:1037 msgid "" ":pep:`366` describes the addition of the ``__package__`` attribute for " "explicit relative imports in main modules." msgstr ":pep:`366` 描述了新增的 ``__package__`` 属性,用于在模块中的显式相对导入。" #: ../../reference/import.rst:1040 msgid "" ":pep:`328` introduced absolute and explicit relative imports and initially " "proposed ``__name__`` for semantics :pep:`366` would eventually specify for " "``__package__``." msgstr "" ":pep:`328` 引入了绝对和显式相对导入,并初次提出了 ``__name__`` 语义,最终由 :pep:`366` 为 " "``__package__`` 加入规范描述。" #: ../../reference/import.rst:1044 msgid ":pep:`338` defines executing modules as scripts." msgstr ":pep:`338` 定义了将模块作为脚本执行。" #: ../../reference/import.rst:1046 msgid "" ":pep:`451` adds the encapsulation of per-module import state in spec " "objects. It also off-loads most of the boilerplate responsibilities of " "loaders back onto the import machinery. These changes allow the deprecation" " of several APIs in the import system and also addition of new methods to " "finders and loaders." msgstr "" ":pep:`451` 在 spec 对象中增加了对每个模块导入状态的封装。 它还将加载器的大部分样板责任移交回导入机制中。 " "这些改变允许弃用导入系统中的一些 API 并为查找器和加载器增加一些新的方法。" #: ../../reference/import.rst:1053 msgid "Footnotes" msgstr "备注" #: ../../reference/import.rst:1054 msgid "See :class:`types.ModuleType`." msgstr "参见 :class:`types.ModuleType`。" #: ../../reference/import.rst:1056 msgid "" "The importlib implementation avoids using the return value directly. " "Instead, it gets the module object by looking the module name up in " ":data:`sys.modules`. The indirect effect of this is that an imported module" " may replace itself in :data:`sys.modules`. This is implementation-specific" " behavior that is not guaranteed to work in other Python implementations." msgstr "" "importlib 实现避免直接使用返回值。 而是通过在 :data:`sys.modules` 中查找模块名称来获取模块对象。 " "这种方式的间接影响是被导入的模块可能在 :data:`sys.modules` 中替换其自身。 这属于具体实现的特定行为,不保证能在其他 Python " "实现中起作用。" #: ../../reference/import.rst:1063 msgid "" "In legacy code, it is possible to find instances of " ":class:`imp.NullImporter` in the :data:`sys.path_importer_cache`. It is " "recommended that code be changed to use ``None`` instead. See " ":ref:`portingpythoncode` for more details." msgstr "" "在遗留代码中,有可能在 :data:`sys.path_importer_cache` 中找到 :class:`imp.NullImporter` " "的实例。 建议将这些代码修改为使用 ``None`` 代替。 详情参见 :ref:`portingpythoncode`。" #: ../../reference/import.rst:8 msgid "import machinery" msgstr "导入机制" #: ../../reference/import.rst:64 ../../reference/import.rst:95 #: ../../reference/import.rst:129 msgid "package" msgstr "包" #: ../../reference/import.rst:95 msgid "regular" msgstr "常规" #: ../../reference/import.rst:129 msgid "namespace" msgstr "namespace -- 命名空间" #: ../../reference/import.rst:129 msgid "portion" msgstr "portion -- 部分" #: ../../reference/import.rst:175 msgid "sys.modules" msgstr "sys.modules" #: ../../reference/import.rst:210 ../../reference/import.rst:276 msgid "finder" msgstr "finder -- 查找器" #: ../../reference/import.rst:210 msgid "loader" msgstr "loader -- 加载器" #: ../../reference/import.rst:210 msgid "module spec" msgstr "module spec -- 模块规格" #: ../../reference/import.rst:249 msgid "import hooks" msgstr "导入钩子" #: ../../reference/import.rst:249 msgid "meta hooks" msgstr "元钩子" #: ../../reference/import.rst:249 msgid "path hooks" msgstr "路径钩子" #: ../../reference/import.rst:249 msgid "hooks" msgstr "钩子" #: ../../reference/import.rst:249 msgid "import" msgstr "import" #: ../../reference/import.rst:249 msgid "meta" msgstr "元数据" #: ../../reference/import.rst:249 msgid "path" msgstr "path" #: ../../reference/import.rst:276 msgid "sys.meta_path" msgstr "sys.meta_path" #: ../../reference/import.rst:276 msgid "find_spec" msgstr "find_spec" #: ../../reference/import.rst:727 msgid "path based finder" msgstr "path based finder -- 基于路径的查找器" #: ../../reference/import.rst:776 msgid "sys.path" msgstr "sys.path" #: ../../reference/import.rst:776 msgid "sys.path_hooks" msgstr "sys.path_hooks" #: ../../reference/import.rst:776 msgid "sys.path_importer_cache" msgstr "sys.path_importer_cache" #: ../../reference/import.rst:776 msgid "PYTHONPATH" msgstr "PYTHONPATH"