importlib
--- import
的实现¶
3.1 新版功能.
概述¶
importlib
包的目的有两个。 第一个目的是在 Python 源代码中提供 import
语句的实现(并且因此而扩展 __import__()
函数)。 这提供了一个可移植到任何 Python 解释器的 import
实现。 相比使用 Python 以外的编程语言实现方式,这一实现更加易于理解。
第二个目的是实现 import
的部分被公开在这个包中,使得用户更容易创建他们自己的自定义对象 (通常被称为 importer) 来参与到导入过程中。
参见
- import 语句
import
语句的语言参考- 包规格说明
包的初始规范。自从编写这个文档开始,一些语义已经发生改变了(比如基于
sys.modules
中None
的重定向)。__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.
import_module
(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.
find_loader
(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
语句,就可以测试表的存在并且跳过它的初始化,如果有需要的话:try: cache except NameError: cache = {}
重新加载内置的或者动态加载模块,通常来说不是很有用处。不推荐重新加载"
sys
,__main__
,builtins
和其它关键模块。在很多例子中,扩展模块并不是设计为不止一次的初始化,并且当重新加载时,可能会以任意方式失败。如果一个模块使用
from
...import
... 导入的对象来自另外一个模块,给其它模块调用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 classes
used by import
. Some subclasses of the core abstract base classes
are also provided to help in implementing the core ABCs.
ABC 类的层次结构:
object
+-- Finder (deprecated)
| +-- MetaPathFinder
| +-- PathEntryFinder
+-- Loader
+-- ResourceLoader --------+
+-- InspectLoader |
+-- ExecutionLoader --+
+-- FileLoader
+-- SourceLoader
-
class
importlib.abc.
Finder
¶ 代表 finder 的一个抽象基类
3.3 版后已移除: 使用
MetaPathFinder
或PathEntryFinder
来代替。-
abstractmethod
find_module
(fullname, path=None)¶ 为指定的模块查找 loader 定义的抽象方法。本来是在 PEP 302 指定的,这个方法是在
sys.meta_path
和基于路径的导入子系统中使用。在 3.4 版更改: 当被调用的时候,返回
None
而不是引发NotImplementedError
。
-
abstractmethod
-
class
importlib.abc.
MetaPathFinder
¶ 代表 meta path finder 的一个抽象基类。 为了保持兼容性,这是
Finder
的一个子类。3.3 新版功能.
-
find_spec
(fullname, path, target=None)¶ An abstract method for finding a spec for the specified module. If this is a top-level import, path will be
None
. Otherwise, this is a search for a subpackage or module and path will be the value of__path__
from the parent package. If a spec cannot be found,None
is returned. When passed in,target
is a module object that the finder may use to make a more educated guess about what spec to return.importlib.util.spec_from_loader()
may be useful for implementing concreteMetaPathFinders
.3.4 新版功能.
-
find_module
(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 新版功能.
-
find_spec
(fullname, target=None)¶ An abstract method for finding a spec for the specified module. The finder will search for the module only within the path entry to which it is assigned. If a spec cannot be found,
None
is returned. When passed in,target
is a module object that the finder may use to make a more educated guess about what spec to return.importlib.util.spec_from_loader()
may be useful for implementing concretePathEntryFinders
.3.4 新版功能.
-
find_loader
(fullname)¶ 一个用于在模块中查找一个 loader 的遗留方法。 返回一个
(loader, portion)
的2元组,portion
是一个贡献给命名空间包部分的文件系统位置的序列。 加载器可能是None
,同时正在指定的portion
表示的是贡献给命名空间包的文件系统位置。portion
可以使用一个空列表来表示加载器不是命名空间包的一部分。 如果loader
是None
并且portion
是一个空列表,那么命名空间包中无加载器或者文件系统位置可查找到(即在那个模块中未能找到任何东西)。如果定义了
find_spec()
,则提供了向后兼容的功能。在 3.4 版更改: 返回
(None, [])
而不是引发NotImplementedError
。 当可于提供相应的功能的时候,使用find_spec()
。3.4 版后已移除: 使用
find_spec()
来代替。
-
find_module
(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()
方法。-
create_module
(spec)¶ 当导入一个模块的时候,一个返回将要使用的那个模块对象的方法。这个方法可能返回
None
,这暗示着应该发生默认的模块创建语义。"3.4 新版功能.
在 3.5 版更改: 从 Python 3.6 开始,当定义了
exec_module()
的时候,这个方法将不会是可选的。
-
exec_module
(module)¶ 当一个模块被导入或重新加载时,一个抽象方法在它自己的命名空间中执行那个模块。当调用
exec_module()
的时候,那个模块应该已经被初始化 了。当这个方法存在时,必须定义create_module()
。3.4 新版功能.
在 3.6 版更改:
create_module()
也必须被定义。
-
load_module
(fullname)¶ 用于加载一个模块的传统方法。如果这个模块不能被导入,将引起
ImportError
异常,否则返回那个被加载的模块。如果请求的模块已经存在
sys.modules
,应该使用并且重新加载那个模块。 否则加载器应该是创建一个新的模块并且在任何家过程开始之前将这个新模块插入到sys.modules
中,来阻止递归导入。 如果加载器插入了一个模块并且加载失败了,加载器必须从sys.modules
中将这个模块移除。在加载器开始执行之前,已经在sys.modules
中的模块应该被忽略 (查看importlib.util.module_for_loader()
)。加载器应该在模块上面设置几个属性。(要知道当重新加载一个模块的时候,那些属性某部分可以改变):
__name__
模块的名字
__file__
模块数据存储的路径(不是为了内置的模块而设置)
__cached__
被存储或应该被存储的模块的编译版本的路径(当这个属性不恰当的时候不设置)。
__path__
指定在一个包中搜索路径的一个字符串列表。这个属性不在模块上面进行设置。
__package__
The fully-qualified name of the package under which the module was loaded as a submodule (or the empty string for top-level modules). For packages, it is the same as
__name__
. Theimportlib.util.module_for_loader()
decorator can handle the details for__package__
.
__loader__
用来加载那个模块的加载器。
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() 所有其他的责任。
-
module_repr
(module)¶ 一个遗留方法,在实现时计算并返回给定模块的 repr,作为字符串。 模块类型的默认 repr() 将根据需要使用此方法的结果。
3.3 新版功能.
在 3.4 版更改: 是可选的方法而不是一个抽象方法。
3.4 版后已移除: 现在导入机制会自动地关注这个方法。
-
-
class
importlib.abc.
ResourceReader
¶ Superseded by TraversableReader
提供读取 resources 能力的一个 abstract base class 。
从这个 ABC 的视角出发,resource 指一个包附带的二进制文件。常见的如在包的
__init__.py
文件旁的数据文件。这个类存在的目的是为了将对数据文件的访问进行抽象,这样包就和其数据文件的存储方式无关了。不论这些文件是存放在一个 zip 文件里还是直接在文件系统内。对于该类中的任一方法,resource 参数的值都需要是一个在概念上表示文件名称的 path-like object。 这意味着任何子目录的路径都不该出现在 resouce 参数值内。 因为对于阅读器而言,包的位置就代表着「目录」。 因此目录和文件名就分别对应于包和资源。 这也是该类的实例都需要和一个包直接关联(而不是潜在指代很多包或者一整个模块)的原因。
想支持资源读取的加载器需要提供一个返回实现了此 ABC 的接口的
get_resource_reader(fullname)
方法。如果通过全名指定的模块不是一个包,这个方法应该返回None
。 当指定的模块是一个包时,应该只返回一个与这个抽象类ABC兼容的对象。3.7 新版功能.
-
abstractmethod
open_resource
(resource)¶ 返回一个打开的 file-like object 用于 resource 的二进制读取。
如果无法找到资源,将会引发
FileNotFoundError
。
-
abstractmethod
resource_path
(resource)¶ 返回 resource 的文件系统路径。
如果资源并不实际存在于文件系统中,将会引发
FileNotFoundError
。
-
abstractmethod
is_resource
(name)¶ 如果*name* 被视作资源,则返回True。如果*name*不存在,则引发
FileNotFoundError
异常。
-
abstractmethod
contents
()¶ 反回由字符串组成的 iterable,表示这个包的所有内容。 请注意并不要求迭代器返回的所有名称都是实际的资源,例如返回
is_resource()
为假值的名称也是可接受的。允许非资源名字被返回是为了允许存储的一个包和它的资源的方式是已知先验的并且非资源名字会有用的情况。比如,允许返回子目录名字,目的是当得知包和资源存储在文件系统上面的时候,能够直接使用子目录的名字。
这个抽象方法返回了一个不包含任何内容的可迭代对象。
-
abstractmethod
-
class
importlib.abc.
ResourceLoader
¶ 一个 loader 的抽象基类,它实现了可选的 PEP 302 协议用于从存储后端加载任意资源。
3.7 版后已移除: 由于要支持使用
importlib.abc.ResourceReader
类来加载资源,这个 ABC 已经被弃用了。-
abstractmethod
get_data
(path)¶ 一个用于返回位于 path 的字节数据的抽象方法。有一个允许存储任意数据的类文件存储后端的加载器能够实现这个抽象方法来直接访问这些被存储的数据。如果不能够找到 path,则会引发
OSError
异常。path 被希望使用一个模块的__file
属性或来自一个包的__path__
来构建。在 3.4 版更改: 引发
OSError
异常而不是NotImplementedError
异常。
-
abstractmethod
-
class
importlib.abc.
InspectLoader
¶ 一个实现加载器检查模块可选的 PEP 302 协议的 loader 的抽象基类。
-
get_code
(fullname)¶ 返回一个模块的代码对象,或如果模块没有一个代码对象(例如,对于内置的模块来说,这会是这种情况),则为
None
。 如果加载器不能找到请求的模块,则引发ImportError
异常。注解
当这个方法有一个默认的实现的时候,出于性能方面的考虑,如果有可能的话,建议覆盖它。
在 3.4 版更改: 不再抽象并且提供一个具体的实现。
-
abstractmethod
get_source
(fullname)¶ 一个返回模块源的抽象方法。使用 universal newlines 作为文本字符串被返回,将所有可识别行分割符翻译成
'\n'
字符。 如果没有可用的源(例如,一个内置模块),则返回None
。 如果加载器不能找到指定的模块,则引发ImportError
异常。在 3.4 版更改: 引发
ImportError
而不是NotImplementedError
。
-
is_package
(fullname)¶ 一个抽象方法,如果这个模块是一个包则返回真值,否则返回假值。 如果 loader 不能找到这个模块,则引发
ImportError
。在 3.4 版更改: 引发
ImportError
而不是NotImplementedError
。
-
static
source_to_code
(data, path='<string>')¶ 创建一个来自Python源码的代码对象。
参数 data 可以是任意
compile()
函数支持的类型(例如字符串或字节串)。 参数 path 应该是源代码来源的路径,这可能是一个抽象概念(例如位于一个 zip 文件中)。在有后续代码对象的情况下,可以在一个模块中通过运行``exec(code, module.__dict__)``来执行它。
3.4 新版功能.
在 3.5 版更改: 使得这个方法变成静态的。
-
exec_module
(module)¶ Loader.exec_module()
的实现。3.4 新版功能.
-
load_module
(fullname)¶ Loader.load_module()
的实现。3.4 版后已移除: 使用
exec_module()
来代替。
-
-
class
importlib.abc.
ExecutionLoader
¶ 一个继承自
InspectLoader
的抽象基类,当被实现时,帮助一个模块作为脚本来执行。 这个抽象基类表示可选的 PEP 302 协议。-
abstractmethod
get_filename
(fullname)¶ 一个用来为指定模块返回
__file__
的值的抽象方法。如果无路径可用,则引发ImportError
。如果源代码可用,那么这个方法返回源文件的路径,不管是否是用来加载模块的字节码。
在 3.4 版更改: 引发
ImportError
而不是NotImplementedError
。
-
abstractmethod
-
class
importlib.abc.
FileLoader
(fullname, path)¶ 一个继承自
ResourceLoader
和ExecutionLoader
,提供ResourceLoader.get_data()
和ExecutionLoader.get_filename()
具体实现的抽象基类。参数*fullname*是加载器要处理的模块的完全解析的名字。参数*path*是模块文件的路径。
3.3 新版功能.
-
name
¶ 加载器可以处理的模块的名字。
-
path
¶ 模块的文件路径
-
load_module
(fullname)¶ 调用super的``load_module()``。
3.4 版后已移除: 使用
Loader.exec_module()
来代替。
-
abstractmethod
get_data
(path)¶ 读取 path 作为二进制文件并且返回来自它的字节数据。
-
-
class
importlib.abc.
SourceLoader
¶ 一个用于实现源文件(和可选地字节码)加载的抽象基类。这个类继承自
ResourceLoader
和ExecutionLoader
,需要实现:ExecutionLoader.get_filename()
应该是只返回源文件的路径;不支持无源加载。
由这个类定义的抽象方法用来添加可选的字节码文件支持。不实现这些可选的方法(或导致它们引发
NotImplementedError
异常)导致这个加载器只能与源代码一起工作。 实现这些方法允许加载器能与源 和 字节码文件一起工作。不允许只提供字节码的 无源式 加载。字节码文件是通过移除 Python 编译器的解析步骤来加速加载的优化,并且因此没有开放出字节码专用的 API。-
path_stats
(path)¶ 返回一个包含关于指定路径的元数据的
dict
的可选的抽象方法。 支持的字典键有:'mtime'
(必选项): 一个表示源码修改时间的整数或浮点数;'size'
(可选项):源码的字节大小。
字典中任何其他键会被忽略,以允许将来的扩展。 如果不能处理该路径,则会引发
OSError
。3.3 新版功能.
在 3.4 版更改: 引发
OSError
而不是NotImplemented
。
-
path_mtime
(path)¶ 返回指定文件路径修改时间的可选的抽象方法。
3.3 版后已移除: 在有了
path_stats()
的情况下,这个方法被弃用了。 没必要去实现它了,但是为了兼容性,它依然处于可用状态。 如果文件路径不能被处理,则引发OSError
异常。在 3.4 版更改: 引发
OSError
而不是NotImplemented
。
-
set_data
(path, data)¶ 往一个文件路径写入指定字节的的可选的抽象方法。任何中间不存在的目录不会被自动创建。
由于路径是只读的,当写入的路径产生错误时(
errno.EACCES
/PermissionError
),不会传播异常。在 3.4 版更改: 当被调用时,不再引起
NotImplementedError
异常。
-
get_code
(fullname)¶ InspectLoader.get_code()
的具体实现。
-
exec_module
(module)¶ Loader.exec_module()
的具体实现。3.4 新版功能.
-
load_module
(fullname)¶ Concrete implementation of
Loader.load_module()
.3.4 版后已移除: 使用
exec_module()
来代替。
-
get_source
(fullname)¶ InspectLoader.get_source()
的具体实现。
-
is_package
(fullname)¶ InspectLoader.is_package()
的具体实现。一个模块被确定为一个包的条件是:它的文件路径(由ExecutionLoader.get_filename()
提供)当文件扩展名被移除时是一个命名为__init__
的文件,并且 这个模块名字本身不是以``__init__``结束。
-
class
importlib.abc.
Traversable
¶ An object with a subset of pathlib.Path methods suitable for traversing directories and opening files.
3.9 新版功能.
-
class
importlib.abc.
TraversableReader
¶ An abstract base class for resource readers capable of serving the
files
interface. Subclasses ResourceReader and provides concrete implementations of the ResourceReader's abstract methods. Therefore, any loader supplying TraversableReader also supplies ResourceReader.3.9 新版功能.
importlib.resources
-- 资源¶
源码: Lib/importlib/resources.py
3.7 新版功能.
这个模块使得Python的导入系统提供了访问*包*内的*资源*的功能。如果能够导入一个包,那么就能够访问那个包里面的资源。资源可以以二进制或文本模式方式被打开或读取。
资源非常类似于目录内部的文件,要牢记的是这仅仅是一个比喻。资源和包不是与文件系统上的物理文件和目录一样存在着。
注解
This module provides functionality similar to pkg_resources Basic Resource Access without the performance overhead of that package. This makes reading resources included in packages easier, with more stable and consistent semantics.
The standalone backport of this module provides more information on using importlib.resources and migrating 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 asUnion[str, ModuleType]
. This means that where the function describes accepting aPackage
, you can pass in either a string or a module. Module objects must have a resolvable__spec__.submodule_search_locations
that is notNone
.
-
importlib.resources.
Resource
¶ This type describes the resource names passed into the various functions in this package. This is defined as
Union[str, os.PathLike]
.
The following functions are available.
-
importlib.resources.
files
(package)¶ Returns an
importlib.resources.abc.Traversable
object representing the resource container for the package (think directory) and its resources (think files). A Traversable may contain other containers (think subdirectories).package is either a name or a module object which conforms to the
Package
requirements.3.9 新版功能.
-
importlib.resources.
open_binary
(package, resource)¶ Open for binary reading the resource within package.
package is either a name or a module object which conforms to the
Package
requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). This function returns atyping.BinaryIO
instance, a binary I/O stream open for reading.
-
importlib.resources.
open_text
(package, resource, encoding='utf-8', errors='strict')¶ Open for text reading the resource within package. By default, the resource is opened for reading as UTF-8.
package is either a name or a module object which conforms to the
Package
requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). encoding and errors have the same meaning as with built-inopen()
.This function returns a
typing.TextIO
instance, a text I/O stream open for reading.
-
importlib.resources.
read_binary
(package, resource)¶ Read and return the contents of the resource within package as
bytes
.package is either a name or a module object which conforms to the
Package
requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). This function returns the contents of the resource asbytes
.
-
importlib.resources.
read_text
(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 the
Package
requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). encoding and errors have the same meaning as with built-inopen()
. This function returns the contents of the resource asstr
.
-
importlib.resources.
path
(package, resource)¶ Return the path to the resource as an actual file system path. This function returns a context manager for use in a
with
statement. The context manager provides apathlib.Path
object.Exiting the context manager cleans up any temporary file created when the resource needs to be extracted from e.g. a zip file.
package is either a name or a module object which conforms to the
Package
requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory).
-
importlib.resources.
is_resource
(package, name)¶ Return
True
if there is a resource named name in the package, otherwiseFalse
. 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 iterable returns
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 the
Package
requirements.
importlib.machinery
-- Importers and path hooks¶
Source code: Lib/importlib/machinery.py
This module contains the various objects that help import
find and load modules.
-
importlib.machinery.
SOURCE_SUFFIXES
¶ A list of strings representing the recognized file suffixes for source modules.
3.3 新版功能.
-
importlib.machinery.
DEBUG_BYTECODE_SUFFIXES
¶ A list of strings representing the file suffixes for non-optimized bytecode modules.
3.3 新版功能.
3.5 版后已移除: Use
BYTECODE_SUFFIXES
instead.
-
importlib.machinery.
OPTIMIZED_BYTECODE_SUFFIXES
¶ A list of strings representing the file suffixes for optimized bytecode modules.
3.3 新版功能.
3.5 版后已移除: Use
BYTECODE_SUFFIXES
instead.
-
importlib.machinery.
BYTECODE_SUFFIXES
¶ A list of strings representing the recognized file suffixes for bytecode modules (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 for extension modules.
3.3 新版功能.
-
importlib.machinery.
all_suffixes
()¶ Returns a combined list of strings representing all file suffixes for modules recognized by the standard import machinery. This is a helper for code which simply needs to know if a filesystem path potentially refers to a module without needing any details on the kind of module (for example,
inspect.getmodulename()
).3.3 新版功能.
-
class
importlib.machinery.
BuiltinImporter
¶ An importer for built-in modules. All known built-in modules are listed 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 for instantiation.
在 3.5 版更改: As part of PEP 489, the builtin importer now implements
Loader.create_module()
andLoader.exec_module()
-
class
importlib.machinery.
FrozenImporter
¶ An importer for frozen modules. This class implements the
importlib.abc.MetaPathFinder
andimportlib.abc.InspectLoader
ABCs.Only class methods are defined by this class to alleviate the need for instantiation.
在 3.4 版更改: Gained
create_module()
andexec_module()
methods.
-
class
importlib.machinery.
WindowsRegistryFinder
¶ Finder for modules declared in the Windows registry. This class implements the
importlib.abc.MetaPathFinder
ABC.Only class methods are defined by this class to alleviate the need for instantiation.
3.3 新版功能.
3.6 版后已移除: Use
site
configuration instead. Future versions of Python may not enable this finder by default.
-
class
importlib.machinery.
PathFinder
¶ A Finder for
sys.path
and package__path__
attributes. This class implements theimportlib.abc.MetaPathFinder
ABC.Only class methods are defined by this class to alleviate the need for instantiation.
-
classmethod
find_spec
(fullname, path=None, target=None)¶ Class method that attempts to find a spec for the module specified by fullname on
sys.path
or, if defined, on path. For each path entry that is searched,sys.path_importer_cache
is checked. If a non-false object is found then it is used as the path entry finder to look for the module being searched for. If no entry is found insys.path_importer_cache
, thensys.path_hooks
is searched for a finder for the path entry and, if found, is stored insys.path_importer_cache
along with being queried about the module. If no finder is ever found thenNone
is both stored 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 cached insys.path_importer_cache
.
-
classmethod
find_module
(fullname, path=None)¶ A legacy wrapper around
find_spec()
.3.4 版后已移除: 使用
find_spec()
来代替。
-
classmethod
invalidate_caches
()¶ Calls
importlib.abc.PathEntryFinder.invalidate_caches()
on all finders stored insys.path_importer_cache
that define the method. Otherwise entries insys.path_importer_cache
set toNone
are deleted.在 3.7 版更改: Entries of
None
insys.path_importer_cache
are deleted.
在 3.4 版更改: Calls objects in
sys.path_hooks
with the current working directory for''
(i.e. the empty string).-
classmethod
-
class
importlib.machinery.
FileFinder
(path, *loader_details)¶ A concrete implementation of
importlib.abc.PathEntryFinder
which caches results from the file system.The path argument is the directory for which the finder is in charge of searching.
The loader_details argument is a variable number of 2-item tuples each containing a loader and a sequence of file suffixes the loader recognizes. The loaders are expected to be callables which accept two arguments of the module's name and the path to the file found.
The finder will cache the directory contents as necessary, making stat calls for each module search to verify the cache is not outdated. Because cache staleness relies upon the granularity of the operating system's state information of the file system, there is a potential race condition of searching for a module, creating a new file, and then searching for the module the new file represents. If the operations happen fast enough to fit within the granularity of stat calls, then the module search will fail. To prevent this from happening, when you create a module dynamically, make sure to call
importlib.invalidate_caches()
.3.3 新版功能.
-
path
¶ The path the finder will search in.
-
find_spec
(fullname, target=None)¶ Attempt to find the spec to handle fullname within
path
.3.4 新版功能.
-
invalidate_caches
()¶ Clear out the internal cache.
-
classmethod
path_hook
(*loader_details)¶ A class method which returns a closure for use on
sys.path_hooks
. An instance ofFileFinder
is returned by the closure using the path 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
by subclassingimportlib.abc.FileLoader
and providing some concrete implementations of other methods.3.3 新版功能.
-
name
¶ The name of the module that this loader will handle.
-
path
¶ The path to the source file.
-
path_stats
(path)¶ Concrete implementation of
importlib.abc.SourceLoader.path_stats()
.
-
set_data
(path, data)¶ Concrete implementation of
importlib.abc.SourceLoader.set_data()
.
-
load_module
(name=None)¶ Concrete implementation of
importlib.abc.Loader.load_module()
where specifying 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 can import bytecode files (i.e. no source code files exist).Please note that direct use of bytecode files (and thus not source code files) inhibits your modules from being usable by all Python implementations or new versions of Python which change the bytecode format.
3.3 新版功能.
-
name
¶ The name of the module the loader will handle.
-
path
¶ The path to the bytecode file.
-
get_source
(fullname)¶ Returns
None
as bytecode files have no source when this loader is used.
-
load_module
(name=None)¶
Concrete implementation of
importlib.abc.Loader.load_module()
where specifying 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
for extension modules.The fullname argument specifies the name of the module the loader is to support. 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.
-
create_module
(spec)¶ Creates the module object from the given specification in accordance with PEP 489.
3.5 新版功能.
-
is_package
(fullname)¶ Returns
True
if the file path points to a package's__init__
module based onEXTENSION_SUFFIXES
.
-
get_code
(fullname)¶ Returns
None
as extension modules lack a code object.
-
get_source
(fullname)¶ Returns
None
as extension modules do not have source code.
-
-
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 is typically exposed as the module's
__spec__
attribute. In the descriptions below, the names in parentheses give the corresponding attribute available directly on the module object. E.g.module.__spec__.origin == module.__file__
. Note however that while the values are usually equivalent, they can differ since there is no synchronization between the two objects. Thus it is possible to update the module's__path__
at runtime, and this will not be automatically reflected in__spec__.submodule_search_locations
.3.4 新版功能.
-
name
¶
(
__name__
)A string for the fully-qualified name of the module.
-
loader
¶
(
__loader__
)The Loader that should be used when loading the module. Finders should always set this.
-
origin
¶
(
__file__
)Name of the place from which the module is loaded, e.g. "builtin" for built-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 (
None
otherwise).-
loader_state
¶
Container of extra module-specific data for use during loading (or
None
).-
cached
¶
(
__cached__
)String for where the compiled module should be stored (or
None
).-
parent
¶
(
__package__
)(Read-only) The fully-qualified name of the package under which the module should be loaded as a submodule (or the empty string for top-level modules). For packages, it is the same as
__name__
.-
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 of an importer.
-
importlib.util.
MAGIC_NUMBER
¶ The bytes which represent the bytecode version number. If you need help with loading/writing bytecode then consider
importlib.abc.SourceLoader
.3.4 新版功能.
-
importlib.util.
cache_from_source
(path, debug_override=None, *, optimization=None)¶ Return the PEP 3147/PEP 488 path to the byte-compiled file associated with the source path. For example, if path is
/foo/bar/baz.py
the return value would be/foo/bar/__pycache__/baz.cpython-32.pyc
for Python 3.2. Thecpython-32
string comes from the current magic tag (seeget_tag()
; ifsys.implementation.cache_tag
is not defined thenNotImplementedError
will be raised).The optimization parameter is used to specify the optimization level of the bytecode file. An empty string represents no optimization, so
/foo/bar/baz.py
with an optimization of''
will result in a bytecode path of/foo/bar/__pycache__/baz.cpython-32.pyc
.None
causes the interpreter's optimization level to be used. Any other value's string representation 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 representation of optimization can only be alphanumeric, elseValueError
is raised.The debug_override parameter is deprecated and can be used to override the system's value for
__debug__
. ATrue
value is the equivalent of setting optimization to the empty string. AFalse
value is the same as setting optimization to1
. If both debug_override an optimization are notNone
thenTypeError
is raised.3.4 新版功能.
在 3.5 版更改: The optimization parameter was added and the debug_override parameter was deprecated.
在 3.6 版更改: 接受一个 类路径对象。
-
importlib.util.
source_from_cache
(path)¶ Given the path to a PEP 3147 file name, return the associated source code file 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 conform to PEP 3147 or PEP 488 format, aValueError
is raised. Ifsys.implementation.cache_tag
is not defined,NotImplementedError
is raised.3.4 新版功能.
在 3.6 版更改: 接受一个 类路径对象。
-
importlib.util.
decode_source
(source_bytes)¶ Decode the given bytes representing source code and return it as a string with universal newlines (as required by
importlib.abc.InspectLoader.get_source()
).3.4 新版功能.
-
importlib.util.
resolve_name
(name, package)¶ Resolve a relative module name to an absolute one.
If name has no leading dots, then name is simply returned. This allows for usage such as
importlib.util.resolve_name('sys', __spec__.parent)
without doing a check to see if the package argument is needed.ImportError
is raised if name is a relative module name but package is a false value (e.g.None
or the empty string).ImportError
is also raised a relative name would escape its containing package (e.g. requesting..bacon
from within thespam
package).3.3 新版功能.
在 3.9 版更改: To improve consistency with import statements, raise
ImportError
instead ofValueError
for invalid relative import attempts.
-
importlib.util.
find_spec
(name, package=None)¶ Find the spec for a module, optionally relative to the specified package name. If the module is in
sys.modules
, thensys.modules[name].__spec__
is returned (unless the spec would beNone
or is not set, in which caseValueError
is raised). Otherwise a search usingsys.meta_path
is done.None
is returned if no spec is found.If name is for a submodule (contains a dot), the parent module is automatically imported.
name and package work the same as for
import_module()
.3.4 新版功能.
在 3.7 版更改: Raises
ModuleNotFoundError
instead ofAttributeError
if package is in fact not a package (i.e. lacks a__path__
attribute).
-
importlib.util.
module_from_spec
(spec)¶ Create a new module based on spec and
spec.loader.create_module
.If
spec.loader.create_module
does not returnNone
, then any pre-existing attributes will not be reset. Also, noAttributeError
will be raised if triggered while accessing spec or setting an attribute on the module.This function is preferred over using
types.ModuleType
to create a new module as spec is used to set as many import-controlled attributes on the module as possible.3.5 新版功能.
-
@
importlib.util.
module_for_loader
¶ A decorator for
importlib.abc.Loader.load_module()
to handle selecting the proper module object to load with. The decorated method is expected to have a call signature taking two positional arguments (e.g.load_module(self, module)
) for which the second argument will be the module object to be used by the loader. Note that the decorator will not work on static methods because of the assumption of two arguments.The decorated method will take in the name of the module to be loaded as expected for a loader. If the module is not found in
sys.modules
then a new one is constructed. Regardless of where the module came from,__loader__
set to self and__package__
is set based on whatimportlib.abc.InspectLoader.is_package()
returns (if available). These attributes are set unconditionally to support reloading.If an exception is raised by the decorated method and a module was added to
sys.modules
, then the module will be removed to prevent a partially initialized module from being in left insys.modules
. If the module was already insys.modules
then it is left alone.在 3.3 版更改:
__loader__
and__package__
are automatically set (when possible).在 3.4 版更改: Set
__name__
,__loader__
__package__
unconditionally to support reloading.3.4 版后已移除: The import machinery now directly performs all the functionality provided by this function.
-
@
importlib.util.
set_loader
¶ A decorator for
importlib.abc.Loader.load_module()
to set the__loader__
attribute on the returned module. If the attribute is already set the decorator does nothing. It is assumed that the first positional argument to the wrapped method (i.e.self
) is what__loader__
should be set to.在 3.4 版更改: Set
__loader__
if set toNone
, as if the attribute does not exist.3.4 版后已移除: The import machinery takes care of this automatically.
-
@
importlib.util.
set_package
¶ A decorator for
importlib.abc.Loader.load_module()
to set the__package__
attribute on the returned module. If__package__
is set and has a value other thanNone
it will not be changed.3.4 版后已移除: The import machinery takes care of this automatically.
-
importlib.util.
spec_from_loader
(name, loader, *, origin=None, is_package=None)¶ A factory function for creating a
ModuleSpec
instance based on a loader. The parameters have the same meaning as they do for ModuleSpec. The function uses available loader APIs, such asInspectLoader.is_package()
, to fill in any missing information on the spec.3.4 新版功能.
-
importlib.util.
spec_from_file_location
(name, location, *, loader=None, submodule_search_locations=None)¶ A factory function for creating a
ModuleSpec
instance based on the path to a file. Missing information will be filled in on the spec by making use of loader APIs and by the implication that the module will be file-based.3.4 新版功能.
在 3.6 版更改: 接受一个 类路径对象。
-
importlib.util.
source_hash
(source_bytes)¶ Return the hash of source_bytes as bytes. A hash-based
.pyc
file embeds thesource_hash()
of the corresponding source file's contents in its header.3.7 新版功能.
-
class
importlib.util.
LazyLoader
(loader)¶ A class which postpones the execution of the loader of a module until the module has an attribute accessed.
This class only works with loaders that define
exec_module()
as control over what module type is used for the module is required. For those same reasons, the loader'screate_module()
method must returnNone
or a type for which its__class__
attribute can be mutated along with not using slots. Finally, modules which substitute the object placed intosys.modules
will not work as there is no way to properly replace 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 for potentially 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 is heavily discouraged due to error messages created during loading being postponed and thus occurring out of context.
3.5 新版功能.
在 3.6 版更改: Began calling
create_module()
, removing the compatibility warning forimportlib.machinery.BuiltinImporter
andimportlib.machinery.ExtensionFileLoader
.-
classmethod
factory
(loader)¶ A static method which returns a callable that creates a lazy loader. This is meant to be used in situations where the loader is passed by class instead of by instance.
suffixes = importlib.machinery.SOURCE_SUFFIXES loader = importlib.machinery.SourceFileLoader lazy_loader = importlib.util.LazyLoader.factory(loader) finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
-
classmethod
示例¶
Importing programmatically¶
To programmatically import a module, use importlib.import_module()
.
import importlib
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 the
import, then you should use importlib.util.find_spec()
.
import importlib.util
import sys
# For illustrative purposes.
name = 'itertools'
if name in sys.modules:
print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
# If you chose to perform the actual import ...
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
print(f"{name!r} has been imported")
else:
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):
import importlib.util
import sys
# For illustrative purposes.
import tokenize
file_path = tokenize.__file__
module_name = tokenize.__name__
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
Setting up an importer¶
For deep customizations of import, you typically want to implement an
importer. This means managing both the finder and loader
side of things. For finders there are two flavours to choose from depending on
your needs: a meta path finder or a path entry finder. The
former is what you would put on sys.meta_path
while the latter is what
you create using a path entry hook on sys.path_hooks
which works
with sys.path
entries to potentially create a finder. This example will
show you how to register your own importers so that import will use them (for
creating an importer for yourself, read the documentation for the appropriate
classes defined within this package):
import importlib.machinery
import sys
# For illustrative purposes only.
SpamMetaPathFinder = importlib.machinery.PathFinder
SpamPathEntryFinder = importlib.machinery.FileFinder
loader_details = (importlib.machinery.SourceFileLoader,
importlib.machinery.SOURCE_SUFFIXES)
# Setting up a meta path finder.
# Make sure to put the finder in the proper location in the list in terms of
# priority.
sys.meta_path.append(SpamMetaPathFinder)
# Setting up a path entry finder.
# Make sure to put the path hook in the proper location in the list in terms
# of priority.
sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))
Approximating importlib.import_module()
¶
Import itself is implemented in Python code, making it possible to
expose most of the import machinery through importlib. The following
helps illustrate the various APIs that importlib exposes by providing an
approximate implementation of
importlib.import_module()
(Python 3.4 and newer for the importlib usage,
Python 3.6 and newer for other parts of the code).
import importlib.util
import sys
def import_module(name, package=None):
"""An approximate implementation of import."""
absolute_name = importlib.util.resolve_name(name, package)
try:
return sys.modules[absolute_name]
except KeyError:
pass
path = None
if '.' in absolute_name:
parent_name, _, child_name = absolute_name.rpartition('.')
parent_module = import_module(parent_name)
path = parent_module.__spec__.submodule_search_locations
for finder in sys.meta_path:
spec = finder.find_spec(absolute_name, path)
if spec is not None:
break
else:
msg = f'No module named {absolute_name!r}'
raise ModuleNotFoundError(msg, name=absolute_name)
module = importlib.util.module_from_spec(spec)
sys.modules[absolute_name] = module
spec.loader.exec_module(module)
if path is not None:
setattr(parent_module, child_name, module)
return module