• importlib —- import 的实现
    • 概述
    • 函数
    • importlib.abc —— 关于导入的抽象基类
    • importlib.resources — 资源
    • importlib.machinery — Importers and path hooks
    • importlib.util — Utility code for importers
    • 示例
      • Importing programmatically
      • Checking if a module can be imported
      • Importing a source file directly
      • Setting up an importer
      • Approximating importlib.import_module()

    importlib —- import 的实现

    3.1 新版功能.

    源代码Lib/importlib/init.py


    概述

    importlib 包的目的有两个。 第一个目的是在 Python 源代码中提供 import 语句的实现(并且因此而扩展 import() 函数)。 这提供了一个可移植到任何 Python 解释器的 import 实现。 相比使用 Python 以外的编程语言实现方式,这一实现更加易于理解。

    第二个目的是实现 import 的部分被公开在这个包中,使得用户更容易创建他们自己的自定义对象 (通常被称为 importer) 来参与到导入过程中。

    参见

    • import 语句
    • import 语句的语言参考

    • 包规格说明

    • 包的初始规范。自从编写这个文档开始,一些语义已经发生改变了(比如基于 sys.modulesNone 的重定向)。

    • import() 函数

    • import 语句是这个函数的语法糖。

    • PEP 235

    • 在忽略大小写的平台上进行导入

    • PEP 263

    • 定义 Python 源代码编码

    • PEP 302

    • 新导入钩子

    • PEP 328

    • 导入:多行和绝对/相对

    • PEP 366

    • 主模块显式相对导入

    • PEP 420

    • 隐式命名空间包

    • PEP 451

    • 导入系统的一个模块规范类型

    • PEP 488

    • 消除PYO文件

    • PEP 489

    • 多阶段扩展模块初始化

    • PEP 552

    • 确定性的 pyc 文件

    • PEP 3120

    • 使用 UTF-8 作为默认的源编码

    • PEP 3147

    • PYC 仓库目录

    函数

    • importlib.import(name, globals=None, locals=None, fromlist=(), level=0)
    • 内置 import() 函数的实现。

    注解

    程序式地导入模块应该使用 import_module() 而不是这个函数。

    • importlib.importmodule(_name, package=None)
    • 导入一个模块。参数 name 指定了以绝对或相对导入方式导入什么模块 (比如要么像这样 pkg.mod 或者这样 ..mod)。如果参数 name 使用相对导入的方式来指定,那么那个参数 packages 必须设置为那个包名,这个包名作为解析这个包名的锚点 (比如 import_module('..mod', 'pkg.subpkg') 将会导入 pkg.mod)。

    import_module() 函数是一个对 importlib.import() 进行简化的包装器。 这意味着该函数的所有主义都来自于 importlib.import()。 这两个函数之间最重要的不同点在于 import_module() 返回指定的包或模块 (例如 pkg.mod),而 import() 返回最高层级的包或模块 (例如 pkg)。

    如果动态导入一个自从解释器开始执行以来被创建的模块(即创建了一个 Python 源代码文件),为了让导入系统知道这个新模块,可能需要调用 invalidate_caches()

    在 3.3 版更改: 父包会被自动导入。

    • importlib.findloader(_name, path=None)
    • 查找一个模块的加载器,可选择地在指定的 path 里面。如果这个模块是在 sys.modules,那么返回 sys.modules[name].loader (除非这个加载器是 None 或者是没有被设置, 在这样的情况下,会引起 ValueError 异常)。 否则使用 sys.meta_path 的一次搜索就结束。如果未发现加载器,则返回 None

    点状的名称没有使得它父包或模块隐式地导入,因为它需要加载它们并且可能不需要。为了适当地导入一个子模块,需要导入子模块的所有父包并且使用正确的参数提供给 path

    3.3 新版功能.

    在 3.4 版更改: 如果没有设置 loader,会引起 ValueError 异常,就像属性设置为 None 的时候一样。

    3.4 版后已移除: 使用 importlib.util.find_spec() 来代替。

    • importlib.invalidate_caches()
    • 使查找器存储在 sys.meta_path 中的内部缓存无效。如果一个查找器实现了 invalidate_caches(),那么它会被调用来执行那个无效过程。 如果创建/安装任何模块,同时正在运行的程序是为了保证所有的查找器知道新模块的存在,那么应该调用这个函数。

    3.3 新版功能.

    • importlib.reload(module)
    • 重新加载之前导入的 module。那个参数必须是一个模块对象,所以它之前必须已经成功导入了。这样做是有用的,如果使用外部编辑器编已经辑过了那个模块的源代码文件并且想在退出 Python 解释器之前试验这个新版本的模块。函数的返回值是那个模块对象(如果重新导入导致一个不同的对象放置在 sys.modules 中,那么那个模块对象是有可能会不同)。

    当执行 reload() 的时候:

    • Python 模块的代码会被重新编译并且那个模块级的代码被重新执行,通过重新使用一开始加载那个模块的 loader,定义一个新的绑定在那个模块字典中的名称的对象集合。扩展模块的init函数不会被调用第二次。

    • 与Python中的所有的其它对象一样,旧的对象只有在它们的引用计数为0之后才会被回收。

    • 模块命名空间中的名称重新指向任何新的或更改后的对象。

    • 其他旧对象的引用(例如那个模块的外部名称)不会被重新绑定到引用的新对象的,并且如果有需要,必须在出现的每个命名空间中进行更新。

    有一些其他注意事项:

    当一个模块被重新加载的时候,它的字典(包含了那个模块的全区变量)会被保留。名称的重新定义会覆盖旧的定义,所以通常来说这不是问题。如果一个新模块没有定义在旧版本模块中定义的名称,则将保留旧版本中的定义。这一特性可用于作为那个模块的优点,如果它维护一个全局表或者对象的缓存 —— 使用 try 语句,就可以测试表的存在并且跳过它的初始化,如果有需要的话:

    1. try:
    2. cache
    3. except NameError:
    4. cache = {}

    重新加载内置的或者动态加载模块,通常来说不是很有用处。不推荐重新加载"sysmainbuiltins 和其它关键模块。在很多例子中,扩展模块并不是设计为不止一次的初始化,并且当重新加载时,可能会以任意方式失败。

    如果一个模块使用 fromimport … 导入的对象来自另外一个模块,给其它模块调用 reload() 不会重新定义来自这个模块的对象 —— 解决这个问题的一种方式是重新执行 from 语句,另一种方式是使用 import 和限定名称(module.name)来代替。

    如果一个模块创建一个类的实例,重新加载定义那个类的模块不影响那些实例的方法定义———它们继续使用旧类中的定义。对于子类来说同样是正确的。

    3.4 新版功能.

    在 3.7 版更改: 当重新加载的那个模块缺少 ModuleSpec 的时候,会引起 ModuleNotFoundError 异常。

    importlib.abc —— 关于导入的抽象基类

    源代码:Lib/importlib/abc.py


    The importlib.abc module contains all of the core abstract base classesused by import. Some subclasses of the core abstract base classesare also provided to help in implementing the core ABCs.

    ABC 类的层次结构:

    1. object
    2. +-- Finder (deprecated)
    3. | +-- MetaPathFinder
    4. | +-- PathEntryFinder
    5. +-- Loader
    6. +-- ResourceLoader --------+
    7. +-- InspectLoader |
    8. +-- ExecutionLoader --+
    9. +-- FileLoader
    10. +-- SourceLoader
    • class importlib.abc.Finder
    • 代表 finder 的一个抽象基类

    3.3 版后已移除: 使用 MetaPathFinderPathEntryFinder 来代替。

    • abstractmethod findmodule(_fullname, path=None)
    • 为指定的模块查找 loader 定义的抽象方法。本来是在 PEP 302 指定的,这个方法是在 sys.meta_path 和基于路径的导入子系统中使用。

    在 3.4 版更改: 当被调用的时候,返回 None 而不是引发 NotImplementedError

    • class importlib.abc.MetaPathFinder
    • 代表 meta path finder 的一个抽象基类。 为了保持兼容性,这是 Finder 的一个子类。

    3.3 新版功能.

    • findspec(_fullname, path, target=None)
    • An abstract method for finding a spec forthe specified module. If this is a top-level import, path willbe None. Otherwise, this is a search for a subpackage ormodule and path will be the value of path from theparent package. If a spec cannot be found, None is returned.When passed in, target is a module object that the finder mayuse to make a more educated guess about what spec to return.importlib.util.spec_from_loader() may be useful for implementingconcrete MetaPathFinders.

    3.4 新版功能.

    • findmodule(_fullname, path)
    • 一个用于查找指定的模块中 loader 的遗留方法。如果这是最高层级的导入,path 的值将会是 None。否则,这是一个查找子包或者模块的方法,并且 path 的值将会是来自父包的 path 的值。如果未发现加载器,返回 None

    如果定义了 find_spec() 方法,则提供了向后兼容的功能。

    在 3.4 版更改: 当调用这个方法的时候返回 None 而不是引发 NotImplementedError。 可以使用 find_spec() 来提供功能。

    3.4 版后已移除: 使用 find_spec() 来代替。

    • invalidate_caches()
    • 当被调用的时候,一个可选的方法应该将查找器使用的任何内部缓存进行无效。将在 sys.meta_path 上的所有查找器的缓存进行无效的时候,这个函数被 importlib.invalidate_caches() 所使用。

    在 3.4 版更改: 当方法被调用的时候,方法返回是 None 而不是 NotImplemented

    • class importlib.abc.PathEntryFinder
    • path entry finder 的一个抽象基类。尽管这个基类和 MetaPathFinder 有一些相似之处,但是 PathEntryFinder 只在由 PathFinder 提供的基于路径导入子系统中使用。这个抽象类是 Finder 的一个子类,仅仅是因为兼容性的原因。

    3.3 新版功能.

    • findspec(_fullname, target=None)
    • An abstract method for finding a spec forthe specified module. The finder will search for the module onlywithin the path entry to which it is assigned. If a speccannot be found, None is returned. When passed in, targetis a module object that the finder may use to make a more educatedguess about what spec to return. importlib.util.spec_from_loader()may be useful for implementing concrete PathEntryFinders.

    3.4 新版功能.

    • findloader(_fullname)
    • 一个用于在模块中查找一个 loader 的遗留方法。 返回一个 (loader, portion) 的2元组,portion 是一个贡献给命名空间包部分的文件系统位置的序列。 加载器可能是 None,同时正在指定的 portion 表示的是贡献给命名空间包的文件系统位置。portion 可以使用一个空列表来表示加载器不是命名空间包的一部分。 如果 loaderNone 并且 portion 是一个空列表,那么命名空间包中无加载器或者文件系统位置可查找到(即在那个模块中未能找到任何东西)。

    如果定义了 find_spec() ,则提供了向后兼容的功能。

    在 3.4 版更改: 返回 (None, []) 而不是引发 NotImplementedError。 当可于提供相应的功能的时候,使用 find_spec()

    3.4 版后已移除: 使用 find_spec() 来代替。

    • findmodule(_fullname)
    • Finder.find_module的具体实现,该方法等价于``self.find_loader(fullname)[0]()

    3.4 版后已移除: 使用 find_spec() 来代替。

    • invalidate_caches()
    • 当被调用的时候,一个可选的方法应该将查找器使用的任何内部缓存进行无效。当将所有缓存的查找器的缓存进行无效的时候,该函数被 PathFinder.invalidate_caches() 使用。
    • class importlib.abc.Loader
    • loader 的抽象基类。 关于一个加载器的实际定义请查看 PEP 302

    加载器想要支持资源读取应该实现一个由 importlib.abc.ResourceReader 指定的get_resource_reader(fullname) 方法。

    在 3.7 版更改: 引入了可选的 get_resource_reader() 方法。

    • createmodule(_spec)
    • 当导入一个模块的时候,一个返回将要使用的那个模块对象的方法。这个方法可能返回 None ,这暗示着应该发生默认的模块创建语义。"

    3.4 新版功能.

    在 3.5 版更改: 从 Python 3.6 开始,当定义了 exec_module() 的时候,这个方法将不会是可选的。

    • execmodule(_module)
    • 当一个模块被导入或重新加载时,一个抽象方法在它自己的命名空间中执行那个模块。当调用 exec_module() 的时候,那个模块应该已经被初始化 了。当这个方法存在时,必须定义 create_module()

    3.4 新版功能.

    在 3.6 版更改: create_module() 也必须被定义。

    • loadmodule(_fullname)
    • 用于加载一个模块的传统方法。如果这个模块不能被导入,将引起 ImportError 异常,否则返回那个被加载的模块。

    如果请求的模块已经存在 sys.modules,应该使用并且重新加载那个模块。 否则加载器应该是创建一个新的模块并且在任何家过程开始之前将这个新模块插入到 sys.modules 中,来阻止递归导入。 如果加载器插入了一个模块并且加载失败了,加载器必须从 sys.modules 中将这个模块移除。在加载器开始执行之前,已经在 sys.modules 中的模块应该被忽略 (查看 importlib.util.module_for_loader())。

    加载器应该在模块上面设置几个属性。(要知道当重新加载一个模块的时候,那些属性某部分可以改变):

    1. -
    2. - [<code>__name__</code>](https://docs.python.org/zh-cn/3/reference/import.html#__name__)
    3. -

    模块的名字

    1. -
    2. - [<code>__file__</code>](https://docs.python.org/zh-cn/3/reference/import.html#__file__)
    3. -

    模块数据存储的路径(不是为了内置的模块而设置)

    1. -
    2. - [<code>__cached__</code>](https://docs.python.org/zh-cn/3/reference/import.html#__cached__)
    3. -

    被存储或应该被存储的模块的编译版本的路径(当这个属性不恰当的时候不设置)。

    1. -
    2. - [<code>__path__</code>](https://docs.python.org/zh-cn/3/reference/import.html#__path__)
    3. -

    指定在一个包中搜索路径的一个字符串列表。这个属性不在模块上面进行设置。

    1. -
    2. - [<code>__package__</code>](https://docs.python.org/zh-cn/3/reference/import.html#__package__)
    3. -

    模块/包的父包。如果这个模块是最上层的,那么它是一个为空字符串的值。 importlib.util.module_for_loader() 装饰器可以处理 package 的细节。

    1. -
    2. - [<code>__loader__</code>](https://docs.python.org/zh-cn/3/reference/import.html#__loader__)
    3. -

    用来加载那个模块的加载器。 importlib.util.module_for_loader() 装饰器可以处理 package 的细节。

    exec_module() 可用的时候,那么则提供了向后兼容的功能。

    在 3.4 版更改: 当这个方法被调用的时候,触发 ImportError 异常而不是 NotImplementedError。当 exec_module() 可用的时候,使用它的功能。

    3.4 版后已移除: 加载模块推荐的使用的 API 是 exec_module() (和 create_module())。 加载器应该实现它而不是 load_module()。 当 exec_module() 被实现的时候,导入机制关心的是 load_module() 所有其他的责任。

    • modulerepr(_module)
    • 一个遗留方法,在实现时计算并返回给定模块的 repr,作为字符串。 模块类型的默认 repr() 将根据需要使用此方法的结果。

    3.3 新版功能.

    在 3.4 版更改: 是可选的方法而不是一个抽象方法。

    3.4 版后已移除: 现在导入机制会自动地关注这个方法。

    • class importlib.abc.ResourceReader
    • 提供读取 resources 能力的一个 abstract base class 。

    从这个 ABC 的视角出发,resource 指一个包附带的二进制文件。常见的如在包的 init.py 文件旁的数据文件。这个类存在的目的是为了将对数据文件的访问进行抽象,这样包就和其数据文件的存储方式无关了。不论这些文件是存放在一个 zip 文件里还是直接在文件系统内。

    对于该类中的任一方法,resource 参数的值都需要是一个在概念上表示文件名称的 path-like object。 这意味着任何子目录的路径都不该出现在 resouce 参数值内。 因为对于阅读器而言,包的位置就代表着「目录」。 因此目录和文件名就分别对应于包和资源。 这也是该类的实例都需要和一个包直接关联(而不是潜在指代很多包或者一整个模块)的原因。

    想支持资源读取的加载器需要提供一个返回实现了此 ABC 的接口的 get_resource_reader(fullname) 方法。如果通过全名指定的模块不是一个包,这个方法应该返回 None。 当指定的模块是一个包时,应该只返回一个与这个抽象类ABC兼容的对象。

    3.7 新版功能.

    • abstractmethod openresource(_resource)
    • 返回一个打开的 file-like object 用于 resource 的二进制读取。

    如果无法找到资源,将会引发 FileNotFoundError

    • abstractmethod resourcepath(_resource)
    • 返回 resource 的文件系统路径。

    如果资源并不实际存在于文件系统中,将会引发 FileNotFoundError

    • abstractmethod isresource(_name)
    • 如果name 被视作资源,则返回True。如果name不存在,则引发 FileNotFoundError 异常。

    • abstractmethod contents()

    • 反回由字符串组成的 iterable,表示这个包的所有内容。 请注意并不要求迭代器返回的所有名称都是实际的资源,例如返回 is_resource() 为假值的名称也是可接受的。

    允许非资源名字被返回是为了允许存储的一个包和它的资源的方式是已知先验的并且非资源名字会有用的情况。比如,允许返回子目录名字,目的是当得知包和资源存储在文件系统上面的时候,能够直接使用子目录的名字。

    这个抽象方法返回了一个不包含任何内容的可迭代对象。

    • class importlib.abc.ResourceLoader
    • 一个 loader 的抽象基类,它实现了可选的 PEP 302 协议用于从存储后端加载任意资源。

    3.7 版后已移除: 由于要支持使用 importlib.abc.ResourceReader 类来加载资源,这个 ABC 已经被弃用了。

    • abstractmethod getdata(_path)
    • 一个用于返回位于 path 的字节数据的抽象方法。有一个允许存储任意数据的类文件存储后端的加载器能够实现这个抽象方法来直接访问这些被存储的数据。如果不能够找到 path,则会引发 OSError 异常。path 被希望使用一个模块的 file 属性或来自一个包的 [path](https://docs.python.org/zh-cn/3/reference/import.html#path__) 来构建。

    在 3.4 版更改: 引发 OSError 异常而不是 NotImplementedError 异常。

    • class importlib.abc.InspectLoader
    • 一个实现加载器检查模块可选的 PEP 302 协议的 loader 的抽象基类。

      • getcode(_fullname)
      • 返回一个模块的代码对象,或如果模块没有一个代码对象(例如,对于内置的模块来说,这会是这种情况),则为 None。 如果加载器不能找到请求的模块,则引发 ImportError 异常。

    注解

    当这个方法有一个默认的实现的时候,出于性能方面的考虑,如果有可能的话,建议覆盖它。

    在 3.4 版更改: 不再抽象并且提供一个具体的实现。

    • abstractmethod getsource(_fullname)
    • 一个返回模块源的抽象方法。使用 universal newlines 作为文本字符串被返回,将所有可识别行分割符翻译成 '\n' 字符。 如果没有可用的源(例如,一个内置模块),则返回 None。 如果加载器不能找到指定的模块,则引发 ImportError 异常。

    在 3.4 版更改: 引发 ImportError 而不是 NotImplementedError

    • ispackage(_fullname)
    • 一个抽象方法,如果这个模块是一个包则返回真值,否则返回假值。 如果 loader 不能找到这个模块,则引发 ImportError

    在 3.4 版更改: 引发 ImportError 而不是 NotImplementedError

    • static sourceto_code(_data, path='')
    • 创建一个来自Python源码的代码对象。

    参数 data 可以是任意 compile() 函数支持的类型(例如字符串或字节串)。 参数 path 应该是源代码来源的路径,这可能是一个抽象概念(例如位于一个 zip 文件中)。

    在有后续代码对象的情况下,可以在一个模块中通过运行exec(code, module.__dict__)来执行它。

    3.4 新版功能.

    在 3.5 版更改: 使得这个方法变成静态的。

    • execmodule(_module)
    • Loader.exec_module() 的实现。

    3.4 新版功能.

    • loadmodule(_fullname)
    • Loader.load_module() 的实现。

    3.4 版后已移除: 使用 exec_module() 来代替。

    • class importlib.abc.ExecutionLoader
    • 一个继承自 InspectLoader 的抽象基类,当被实现时,帮助一个模块作为脚本来执行。 这个抽象基类表示可选的 PEP 302 协议。

      • abstractmethod getfilename(_fullname)
      • 一个用来为指定模块返回 file 的值的抽象方法。如果无路径可用,则引发 ImportError

    如果源代码可用,那么这个方法返回源文件的路径,不管是否是用来加载模块的字节码。

    在 3.4 版更改: 引发 ImportError 而不是 NotImplementedError

    • class importlib.abc.FileLoader(fullname, path)
    • 一个继承自 ResourceLoaderExecutionLoader,提供 ResourceLoader.get_data()ExecutionLoader.get_filename() 具体实现的抽象基类。

    参数fullname是加载器要处理的模块的完全解析的名字。参数path是模块文件的路径。

    3.3 新版功能.

    • name
    • 加载器可以处理的模块的名字。

    • path

    • 模块的文件路径

    • loadmodule(_fullname)

    • 调用super的load_module()

    3.4 版后已移除: 使用 Loader.exec_module() 来代替。

    • abstractmethod getfilename(_fullname)
    • 返回 path

    • abstractmethod getdata(_path)

    • 读取 path 作为二进制文件并且返回来自它的字节数据。
    • class importlib.abc.SourceLoader
    • 一个用于实现源文件(和可选地字节码)加载的抽象基类。这个类继承自 ResourceLoaderExecutionLoader,需要实现:

      • ResourceLoader.get_data()

        • ExecutionLoader.get_filename()
        • 应该是只返回源文件的路径;不支持无源加载。

    由这个类定义的抽象方法用来添加可选的字节码文件支持。不实现这些可选的方法(或导致它们引发 NotImplementedError 异常)导致这个加载器只能与源代码一起工作。 实现这些方法允许加载器能与源 字节码文件一起工作。不允许只提供字节码的 无源式 加载。字节码文件是通过移除 Python 编译器的解析步骤来加速加载的优化,并且因此没有开放出字节码专用的 API。

    • pathstats(_path)
    • 返回一个包含关于指定路径的元数据的 dict 的可选的抽象方法。 支持的字典键有:

      • 'mtime' (必选项): 一个表示源码修改时间的整数或浮点数;

      • 'size' (可选项):源码的字节大小。

    字典中任何其他键会被忽略,以允许将来的扩展。 如果不能处理该路径,则会引发 OSError

    3.3 新版功能.

    在 3.4 版更改: 引发 OSError 而不是 NotImplemented

    • pathmtime(_path)
    • 返回指定文件路径修改时间的可选的抽象方法。

    3.3 版后已移除: 在有了 path_stats() 的情况下,这个方法被弃用了。 没必要去实现它了,但是为了兼容性,它依然处于可用状态。 如果文件路径不能被处理,则引发 OSError 异常。

    在 3.4 版更改: 引发 OSError 而不是 NotImplemented

    • setdata(_path, data)
    • 往一个文件路径写入指定字节的的可选的抽象方法。任何中间不存在的目录不会被自动创建。

    由于路径是只读的,当写入的路径产生错误时(errno.EACCES/PermissionError),不会传播异常。

    在 3.4 版更改: 当被调用时,不再引起 NotImplementedError 异常。

    • getcode(_fullname)
    • InspectLoader.get_code() 的具体实现。

    • execmodule(_module)

    • Loader.exec_module() 的具体实现。

    3.4 新版功能.

    • loadmodule(_fullname)
    • Concrete implementation of Loader.load_module().

    3.4 版后已移除: 使用 exec_module() 来代替。

    • getsource(_fullname)
    • InspectLoader.get_source() 的具体实现。

    • ispackage(_fullname)

    • InspectLoader.is_package() 的具体实现。一个模块被确定为一个包的条件是:它的文件路径(由 ExecutionLoader.get_filename() 提供)当文件扩展名被移除时是一个命名为 init 的文件,并且 这个模块名字本身不是以__init__结束。

    importlib.resources — 资源

    源码:Lib/importlib/resources.py


    3.7 新版功能.

    这个模块使得Python的导入系统提供了访问内的资源的功能。如果能够导入一个包,那么就能够访问那个包里面的资源。资源可以以二进制或文本模式方式被打开或读取。

    资源非常类似于目录内部的文件,要牢记的是这仅仅是一个比喻。资源和包不是与文件系统上的物理文件和目录一样存在着。

    注解

    This module provides functionality similar to pkg_resourcesBasicResource Accesswithout the performance overhead of that package. This makes readingresources included in packages easier, with more stable and consistentsemantics.

    The standalone backport of this module provides more informationon using importlib.resources andmigrating from pkg_resources to importlib.resources.

    加载器想要支持资源读取应该实现一个由 importlib.abc.ResourceReader 指定的get_resource_reader(fullname) 方法。

    The following types are defined.

    • importlib.resources.Package
    • The Package type is defined as Union[str, ModuleType]. This meansthat where the function describes accepting a Package, you can pass ineither a string or a module. Module objects must have a resolvablespec.submodule_search_locations that is not None.

    • importlib.resources.Resource

    • This type describes the resource names passed into the various functionsin this package. This is defined as Union[str, os.PathLike].

    The following functions are available.

    • importlib.resources.openbinary(_package, resource)
    • Open for binary reading the resource within package.

    package is either a name or a module object which conforms to thePackage requirements. resource is the name of the resource to openwithin package; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory). This function returns atyping.BinaryIO instance, a binary I/O stream open for reading.

    • importlib.resources.opentext(_package, resource, encoding='utf-8', errors='strict')
    • Open for text reading the resource within package. By default, theresource is opened for reading as UTF-8.

    package is either a name or a module object which conforms to thePackage requirements. resource is the name of the resource to openwithin package; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory). encoding and _errors_have the same meaning as with built-in open().

    This function returns a typing.TextIO instance, a text I/O stream openfor reading.

    • importlib.resources.readbinary(_package, resource)
    • Read and return the contents of the resource within package asbytes.

    package is either a name or a module object which conforms to thePackage requirements. resource is the name of the resource to openwithin package; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory). This function returns thecontents of the resource as bytes.

    • importlib.resources.readtext(_package, resource, encoding='utf-8', errors='strict')
    • Read and return the contents of resource within package as a str.By default, the contents are read as strict UTF-8.

    package is either a name or a module object which conforms to thePackage requirements. resource is the name of the resource to openwithin package; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory). encoding and _errors_have the same meaning as with built-in open(). This functionreturns the contents of the resource as str.

    • importlib.resources.path(package, resource)
    • Return the path to the resource as an actual file system path. Thisfunction returns a context manager for use in a with statement.The context manager provides a pathlib.Path object.

    Exiting the context manager cleans up any temporary file created when theresource needs to be extracted from e.g. a zip file.

    package is either a name or a module object which conforms to thePackage requirements. resource is the name of the resource to openwithin package; it may not contain path separators and it may not havesub-resources (i.e. it cannot be a directory).

    • importlib.resources.isresource(_package, name)
    • Return True if there is a resource named name in the package,otherwise False. Remember that directories are not resources!package is either a name or a module object which conforms to thePackage requirements.

    • importlib.resources.contents(package)

    • Return an iterable over the named items within the package. The iterablereturns str resources (e.g. files) and non-resources(e.g. directories). The iterable does not recurse into subdirectories.

    package is either a name or a module object which conforms to thePackage requirements.

    importlib.machinery — Importers and path hooks

    Source code:Lib/importlib/machinery.py


    This module contains the various objects that help importfind and load modules.

    • importlib.machinery.SOURCE_SUFFIXES
    • A list of strings representing the recognized file suffixes for sourcemodules.

    3.3 新版功能.

    • importlib.machinery.DEBUG_BYTECODE_SUFFIXES
    • A list of strings representing the file suffixes for non-optimized bytecodemodules.

    3.3 新版功能.

    3.5 版后已移除: Use BYTECODE_SUFFIXES instead.

    • importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES
    • A list of strings representing the file suffixes for optimized bytecodemodules.

    3.3 新版功能.

    3.5 版后已移除: Use BYTECODE_SUFFIXES instead.

    • importlib.machinery.BYTECODE_SUFFIXES
    • A list of strings representing the recognized file suffixes for bytecodemodules (including the leading dot).

    3.3 新版功能.

    在 3.5 版更改: The value is no longer dependent on debug.

    • importlib.machinery.EXTENSION_SUFFIXES
    • A list of strings representing the recognized file suffixes forextension modules.

    3.3 新版功能.

    • importlib.machinery.all_suffixes()
    • Returns a combined list of strings representing all file suffixes formodules recognized by the standard import machinery. This is ahelper for code which simply needs to know if a filesystem pathpotentially refers to a module without needing any details on the kindof module (for example, inspect.getmodulename()).

    3.3 新版功能.

    • class importlib.machinery.BuiltinImporter
    • An importer for built-in modules. All known built-in modules arelisted in sys.builtin_module_names. This class implements theimportlib.abc.MetaPathFinder andimportlib.abc.InspectLoader ABCs.

    Only class methods are defined by this class to alleviate the need forinstantiation.

    在 3.5 版更改: As part of PEP 489, the builtin importer now implementsLoader.create_module() and Loader.exec_module()

    • class importlib.machinery.FrozenImporter
    • An importer for frozen modules. This class implements theimportlib.abc.MetaPathFinder andimportlib.abc.InspectLoader ABCs.

    Only class methods are defined by this class to alleviate the need forinstantiation.

    • class importlib.machinery.WindowsRegistryFinder
    • Finder for modules declared in the Windows registry. This classimplements the importlib.abc.MetaPathFinder ABC.

    Only class methods are defined by this class to alleviate the need forinstantiation.

    3.3 新版功能.

    3.6 版后已移除: Use site configuration instead. Future versions of Python maynot enable this finder by default.

    • class importlib.machinery.PathFinder
    • A Finder for sys.path and package path attributes.This class implements the importlib.abc.MetaPathFinder ABC.

    Only class methods are defined by this class to alleviate the need forinstantiation.

    • classmethod findspec(_fullname, path=None, target=None)
    • Class method that attempts to find a specfor the module specified by fullname on sys.path or, ifdefined, on path. For each path entry that is searched,sys.path_importer_cache is checked. If a non-false objectis found then it is used as the path entry finder to lookfor the module being searched for. If no entry is found insys.path_importer_cache, then sys.path_hooks issearched for a finder for the path entry and, if found, is storedin sys.path_importer_cache along with being queried aboutthe module. If no finder is ever found then None is bothstored in the cache and returned.

    3.4 新版功能.

    在 3.5 版更改: If the current working directory — represented by an empty string —is no longer valid then None is returned but no value is cachedin sys.path_importer_cache.

    • classmethod findmodule(_fullname, path=None)
    • A legacy wrapper around find_spec().

    3.4 版后已移除: 使用 find_spec() 来代替。

    • classmethod invalidate_caches()
    • Calls importlib.abc.PathEntryFinder.invalidate_caches() on allfinders stored in sys.path_importer_cache that define the method.Otherwise entries in sys.path_importer_cache set to None aredeleted.

    在 3.7 版更改: Entries of None in sys.path_importer_cache are deleted.

    在 3.4 版更改: Calls objects in sys.path_hooks with the current workingdirectory for '' (i.e. the empty string).

    • class importlib.machinery.FileFinder(path, *loader_details)
    • A concrete implementation of importlib.abc.PathEntryFinder whichcaches results from the file system.

    The path argument is the directory for which the finder is in charge ofsearching.

    The loader_details argument is a variable number of 2-item tuples eachcontaining a loader and a sequence of file suffixes the loader recognizes.The loaders are expected to be callables which accept two arguments ofthe module's name and the path to the file found.

    The finder will cache the directory contents as necessary, making stat callsfor each module search to verify the cache is not outdated. Because cachestaleness relies upon the granularity of the operating system's stateinformation of the file system, there is a potential race condition ofsearching for a module, creating a new file, and then searching for themodule the new file represents. If the operations happen fast enough to fitwithin the granularity of stat calls, then the module search will fail. Toprevent this from happening, when you create a module dynamically, make sureto call importlib.invalidate_caches().

    3.3 新版功能.

    • path
    • The path the finder will search in.

    • findspec(_fullname, target=None)

    • Attempt to find the spec to handle fullname within path.

    3.4 新版功能.

    • findloader(_fullname)
    • Attempt to find the loader to handle fullname within path.

    • invalidate_caches()

    • Clear out the internal cache.

    • classmethod pathhook(*loaderdetails)

    • A class method which returns a closure for use on sys.path_hooks.An instance of FileFinder is returned by the closure using thepath argument given to the closure directly and _loader_details_indirectly.

    If the argument to the closure is not an existing directory,ImportError is raised.

    • class importlib.machinery.SourceFileLoader(fullname, path)
    • A concrete implementation of importlib.abc.SourceLoader bysubclassing importlib.abc.FileLoader and providing some concreteimplementations of other methods.

    3.3 新版功能.

    • name
    • The name of the module that this loader will handle.

    • path

    • The path to the source file.

    • ispackage(_fullname)

    • Return True if path appears to be for a package.

    • pathstats(_path)

    • Concrete implementation of importlib.abc.SourceLoader.path_stats().

    • setdata(_path, data)

    • Concrete implementation of importlib.abc.SourceLoader.set_data().

    • loadmodule(_name=None)

    • Concrete implementation of importlib.abc.Loader.load_module() wherespecifying the name of the module to load is optional.

    3.6 版后已移除: Use importlib.abc.Loader.exec_module() instead.

    • class importlib.machinery.SourcelessFileLoader(fullname, path)
    • A concrete implementation of importlib.abc.FileLoader which canimport bytecode files (i.e. no source code files exist).

    Please note that direct use of bytecode files (and thus not source codefiles) inhibits your modules from being usable by all Pythonimplementations or new versions of Python which change the bytecodeformat.

    3.3 新版功能.

    • name
    • The name of the module the loader will handle.

    • path

    • The path to the bytecode file.

    • ispackage(_fullname)

    • Determines if the module is a package based on path.

    • getcode(_fullname)

    • Returns the code object for name created from path.

    • getsource(_fullname)

    • Returns None as bytecode files have no source when this loader isused.

    • loadmodule(_name=None)

    • Concrete implementation of importlib.abc.Loader.load_module() wherespecifying the name of the module to load is optional.

    3.6 版后已移除: Use importlib.abc.Loader.exec_module() instead.

    • class importlib.machinery.ExtensionFileLoader(fullname, path)
    • A concrete implementation of importlib.abc.ExecutionLoader forextension modules.

    The fullname argument specifies the name of the module the loader is tosupport. The path argument is the path to the extension module's file.

    3.3 新版功能.

    • name
    • Name of the module the loader supports.

    • path

    • Path to the extension module.

    • createmodule(_spec)

    • Creates the module object from the given specification in accordancewith PEP 489.

    3.5 新版功能.

    • execmodule(_module)
    • Initializes the given module object in accordance with PEP 489.

    3.5 新版功能.

    • ispackage(_fullname)
    • Returns True if the file path points to a package's initmodule based on EXTENSION_SUFFIXES.

    • getcode(_fullname)

    • Returns None as extension modules lack a code object.

    • getsource(_fullname)

    • Returns None as extension modules do not have source code.

    • getfilename(_fullname)

    • 返回 path

    3.4 新版功能.

    • class importlib.machinery.ModuleSpec(name, loader, *, origin=None, loader_state=None, is_package=None)
    • A specification for a module's import-system-related state. This istypically exposed as the module's spec attribute. In thedescriptions below, the names in parentheses give the correspondingattribute available directly on the module object.E.g. module.spec.origin == module.file. Note however thatwhile the values are usually equivalent, they can differ since there isno synchronization between the two objects. Thus it is possible to updatethe module's path at runtime, and this will not be automaticallyreflected in spec.submodule_search_locations.

    3.4 新版功能.

    • name
    • (name)

    A string for the fully-qualified name of the module.

    • loader
    • (loader)

    The loader to use for loading. For namespace packages this should beset to None.

    • origin
    • (file)

    Name of the place from which the module is loaded, e.g. "builtin" forbuilt-in modules and the filename for modules loaded from source.Normally "origin" should be set, but it may be None (the default)which indicates it is unspecified (e.g. for namespace packages).

    • submodule_search_locations
    • (path)

    List of strings for where to find submodules, if a package (Noneotherwise).

    • loader_state
    • Container of extra module-specific data for use during loading (orNone).

    • cached

    • (cached)

    String for where the compiled module should be stored (or None).

    • parent
    • (package)

    (Read-only) Fully-qualified name of the package to which the modulebelongs as a submodule (or None).

    • has_location
    • Boolean indicating whether or not the module's "origin"attribute refers to a loadable location.

    importlib.util — Utility code for importers

    Source code:Lib/importlib/util.py


    This module contains the various objects that help in the construction ofan importer.

    • importlib.util.MAGIC_NUMBER
    • The bytes which represent the bytecode version number. If you need help withloading/writing bytecode then consider importlib.abc.SourceLoader.

    3.4 新版功能.

    • importlib.util.cachefrom_source(_path, debug_override=None, *, optimization=None)
    • Return the PEP 3147/PEP 488 path to the byte-compiled file associatedwith the source path. For example, if path is /foo/bar/baz.py the returnvalue would be /foo/bar/pycache/baz.cpython-32.pyc for Python 3.2.The cpython-32 string comes from the current magic tag (seeget_tag(); if sys.implementation.cache_tag is not defined thenNotImplementedError will be raised).

    The optimization parameter is used to specify the optimization level of thebytecode file. An empty string represents no optimization, so/foo/bar/baz.py with an optimization of '' will result in abytecode path of /foo/bar/pycache/baz.cpython-32.pyc. None causesthe interpreter's optimization level to be used. Any other value's stringrepresentation is used, so /foo/bar/baz.py with an optimization of2 will lead to the bytecode path of/foo/bar/pycache/baz.cpython-32.opt-2.pyc. The string representationof optimization can only be alphanumeric, else ValueError is raised.

    The debug_override parameter is deprecated and can be used to overridethe system's value for debug. A True value is the equivalent ofsetting optimization to the empty string. A False value is the same assetting optimization to 1. If both debug_override an _optimization_are not None then TypeError is raised.

    3.4 新版功能.

    在 3.5 版更改: The optimization parameter was added and the debug_override parameterwas deprecated.

    在 3.6 版更改: 接受一个 类路径对象。

    • importlib.util.sourcefrom_cache(_path)
    • Given the path to a PEP 3147 file name, return the associated source codefile path. For example, if path is/foo/bar/pycache/baz.cpython-32.pyc the returned path would be/foo/bar/baz.py. path need not exist, however if it does not conformto PEP 3147 or PEP 488 format, a ValueError is raised. Ifsys.implementation.cache_tag is not defined,NotImplementedError is raised.

    3.4 新版功能.

    在 3.6 版更改: 接受一个 类路径对象。

    • importlib.util.decodesource(_source_bytes)
    • Decode the given bytes representing source code and return it as a stringwith universal newlines (as required byimportlib.abc.InspectLoader.get_source()).

    3.4 新版功能.

    • importlib.util.resolvename(_name, package)
    • Resolve a relative module name to an absolute one.

    If name has no leading dots, then name is simply returned. Thisallows for usage such asimportlib.util.resolvename('sys', _package) without doing acheck to see if the package argument is needed.

    ValueError is raised if name is a relative module name butpackage is a false value (e.g. None or the empty string).ValueError is also raised a relative name would escape its containingpackage (e.g. requesting ..bacon from within the spam package).

    3.3 新版功能.

    • importlib.util.findspec(_name, package=None)
    • Find the spec for a module, optionally relative tothe specified package name. If the module is in sys.modules,then sys.modules[name].spec is returned (unless the spec would beNone or is not set, in which case ValueError is raised).Otherwise a search using sys.meta_path is done. None isreturned if no spec is found.

    If name is for a submodule (contains a dot), the parent module isautomatically imported.

    name and package work the same as for import_module().

    3.4 新版功能.

    在 3.7 版更改: Raises ModuleNotFoundError instead of AttributeError ifpackage is in fact not a package (i.e. lacks a pathattribute).

    • importlib.util.modulefrom_spec(_spec)
    • Create a new module based on spec andspec.loader.create_module.

    If spec.loader.create_moduledoes not return None, then any pre-existing attributes will not be reset.Also, no AttributeError will be raised if triggered while accessingspec or setting an attribute on the module.

    This function is preferred over using types.ModuleType to create anew module as spec is used to set as many import-controlled attributes onthe module as possible.

    3.5 新版功能.

    • @importlib.util.module_for_loader
    • A decorator for importlib.abc.Loader.load_module()to handle selecting the propermodule object to load with. The decorated method is expected to have a callsignature taking two positional arguments(e.g. load_module(self, module)) for which the second argumentwill be the module object to be used by the loader.Note that the decorator will not work on static methods because of theassumption of two arguments.

    The decorated method will take in the name of the module to be loadedas expected for a loader. If the module is not found insys.modules then a new one is constructed. Regardless of where themodule came from, loader set to self and packageis set based on what importlib.abc.InspectLoader.is_package() returns(if available). These attributes are set unconditionally to supportreloading.

    If an exception is raised by the decorated method and a module was added tosys.modules, then the module will be removed to prevent a partiallyinitialized module from being in left in sys.modules. If the modulewas already in sys.modules then it is left alone.

    在 3.3 版更改: loader and package are automatically set(when possible).

    在 3.4 版更改: Set name, loaderpackageunconditionally to support reloading.

    3.4 版后已移除: The import machinery now directly performs all the functionalityprovided by this function.

    • @importlib.util.set_loader
    • A decorator for importlib.abc.Loader.load_module()to set the loaderattribute on the returned module. If the attribute is already set thedecorator does nothing. It is assumed that the first positional argument tothe wrapped method (i.e. self) is what loader should be setto.

    在 3.4 版更改: Set loader if set to None, as if the attribute does notexist.

    3.4 版后已移除: The import machinery takes care of this automatically.

    • @importlib.util.set_package
    • A decorator for importlib.abc.Loader.load_module() to set thepackage attribute on the returned module. If packageis set and has a value other than None it will not be changed.

    3.4 版后已移除: The import machinery takes care of this automatically.

    • importlib.util.specfrom_loader(_name, loader, *, origin=None, is_package=None)
    • A factory function for creating a ModuleSpec instance basedon a loader. The parameters have the same meaning as they do forModuleSpec. The function uses available loader APIs, such asInspectLoader.is_package(), to fill in any missinginformation on the spec.

    3.4 新版功能.

    • importlib.util.specfrom_file_location(_name, location, *, loader=None, submodule_search_locations=None)
    • A factory function for creating a ModuleSpec instance basedon the path to a file. Missing information will be filled in on thespec by making use of loader APIs and by the implication that themodule will be file-based.

    3.4 新版功能.

    在 3.6 版更改: 接受一个 类路径对象。

    • importlib.util.sourcehash(_source_bytes)
    • Return the hash of source_bytes as bytes. A hash-based .pyc file embedsthe source_hash() of the corresponding source file's contents in itsheader.

    3.7 新版功能.

    • class importlib.util.LazyLoader(loader)
    • A class which postpones the execution of the loader of a module until themodule has an attribute accessed.

    This class only works with loaders that defineexec_module() as control over what module typeis used for the module is required. For those same reasons, the loader'screate_module() method must return None or atype for which its class attribute can be mutated along with notusing slots. Finally, modules which substitute the objectplaced into sys.modules will not work as there is no way to properlyreplace the module references throughout the interpreter safely;ValueError is raised if such a substitution is detected.

    注解

    For projects where startup time is critical, this class allows forpotentially minimizing the cost of loading a module if it is never used.For projects where startup time is not essential then use of this class isheavily discouraged due to error messages created during loading beingpostponed and thus occurring out of context.

    3.5 新版功能.

    在 3.6 版更改: Began calling create_module(), removing thecompatibility warning for importlib.machinery.BuiltinImporter andimportlib.machinery.ExtensionFileLoader.

    • classmethod factory(loader)
    • A static method which returns a callable that creates a lazy loader. Thisis meant to be used in situations where the loader is passed by classinstead of by instance.
    1. suffixes = importlib.machinery.SOURCE_SUFFIXES
    2. loader = importlib.machinery.SourceFileLoader
    3. lazy_loader = importlib.util.LazyLoader.factory(loader)
    4. finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))

    示例

    Importing programmatically

    To programmatically import a module, use importlib.import_module().

    1. import importlib
    2.  
    3. itertools = importlib.import_module('itertools')

    Checking if a module can be imported

    If you need to find out if a module can be imported without actually doing theimport, then you should use importlib.util.find_spec().

    1. import importlib.util
    2. import sys
    3.  
    4. # For illustrative purposes.
    5. name = 'itertools'
    6.  
    7. if name in sys.modules:
    8. print(f"{name!r} already in sys.modules")
    9. elif (spec := importlib.util.find_spec(name)) is not None:
    10. # If you chose to perform the actual import ...
    11. module = importlib.util.module_from_spec(spec)
    12. sys.modules[name] = module
    13. spec.loader.exec_module(module)
    14. print(f"{name!r} has been imported")
    15. else:
    16. print(f"can't find the {name!r} module")

    Importing a source file directly

    To import a Python source file directly, use the following recipe(Python 3.5 and newer only):

    1. import importlib.util
    2. import sys
    3.  
    4. # For illustrative purposes.
    5. import tokenize
    6. file_path = tokenize.__file__
    7. module_name = tokenize.__name__
    8.  
    9. spec = importlib.util.spec_from_file_location(module_name, file_path)
    10. module = importlib.util.module_from_spec(spec)
    11. sys.modules[module_name] = module
    12. spec.loader.exec_module(module)

    Setting up an importer

    For deep customizations of import, you typically want to implement animporter. This means managing both the finder and loaderside of things. For finders there are two flavours to choose from depending onyour needs: a meta path finder or a path entry finder. Theformer is what you would put on sys.meta_path while the latter is whatyou create using a path entry hook on sys.path_hooks which workswith sys.path entries to potentially create a finder. This example willshow you how to register your own importers so that import will use them (forcreating an importer for yourself, read the documentation for the appropriateclasses defined within this package):

    1. import importlib.machinery
    2. import sys
    3.  
    4. # For illustrative purposes only.
    5. SpamMetaPathFinder = importlib.machinery.PathFinder
    6. SpamPathEntryFinder = importlib.machinery.FileFinder
    7. loader_details = (importlib.machinery.SourceFileLoader,
    8. importlib.machinery.SOURCE_SUFFIXES)
    9.  
    10. # Setting up a meta path finder.
    11. # Make sure to put the finder in the proper location in the list in terms of
    12. # priority.
    13. sys.meta_path.append(SpamMetaPathFinder)
    14.  
    15. # Setting up a path entry finder.
    16. # Make sure to put the path hook in the proper location in the list in terms
    17. # of priority.
    18. sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))

    Approximating importlib.import_module()

    Import itself is implemented in Python code, making it possible toexpose most of the import machinery through importlib. The followinghelps illustrate the various APIs that importlib exposes by providing anapproximate implementation ofimportlib.import_module() (Python 3.4 and newer for the importlib usage,Python 3.6 and newer for other parts of the code).

    1. import importlib.util
    2. import sys
    3.  
    4. def import_module(name, package=None):
    5. """An approximate implementation of import."""
    6. absolute_name = importlib.util.resolve_name(name, package)
    7. try:
    8. return sys.modules[absolute_name]
    9. except KeyError:
    10. pass
    11.  
    12. path = None
    13. if '.' in absolute_name:
    14. parent_name, _, child_name = absolute_name.rpartition('.')
    15. parent_module = import_module(parent_name)
    16. path = parent_module.__spec__.submodule_search_locations
    17. for finder in sys.meta_path:
    18. spec = finder.find_spec(absolute_name, path)
    19. if spec is not None:
    20. break
    21. else:
    22. msg = f'No module named {absolute_name!r}'
    23. raise ModuleNotFoundError(msg, name=absolute_name)
    24. module = importlib.util.module_from_spec(spec)
    25. sys.modules[absolute_name] = module
    26. spec.loader.exec_module(module)
    27. if path is not None:
    28. setattr(parent_module, child_name, module)
    29. return module