importlib --- import の実装¶
Added in version 3.1.
ソースコード: Lib/importlib/__init__.py
はじめに¶
importlib パッケージの目的は3つあります。
1つ目は Python ソースコード中にある import 文の(そして、拡張として、 __import__() 関数の)実装を提供することです。このパッケージは import 文の、どの Python インタープリターでも動作する実装を提供します。また、 Python 以外の言語で実装されたどの実装よりも把握しやすい実装を提供します。
2つ目の目的は、このパッケージが公開している import を実装するための要素を利用して、(インポーター として知られる) インポートプロセスで動作するカスタムのオブジェクトを実装しやすくすることです。
Three, the package contains modules exposing additional functionality for managing aspects of Python packages:
importlib.metadatapresents access to metadata from third-party distributions.importlib.resourcesprovides routines for accessing non-code "resources" from Python packages.
参考
- import 文
import文の言語リファレンス。- Packages specification
パッケージの元の仕様。幾つかの動作はこの仕様が書かれた頃から変更されています (例:
sys.modulesでNoneに基づくリダイレクト)。__import__()関数import文はこの関数のシンタックスシュガーです。- sys.path モジュール検索パスの初期化
The initialization of
sys.path.- PEP 235
大文字小文字を区別しないプラットフォームでのインポート
- PEP 263
Python のソースコードのエンコーディング
- PEP 302
新しいインポートフック
- PEP 328
複数行のインポートと、絶対/相対インポート
- PEP 366
main モジュールの明示的な相対インポート
- PEP 420
暗黙的な名前空間パッケージ
- PEP 451
インポートシステムのための ModuleSpec 型
- 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 が相対表現で与えられたら、package 引数を、パッケージ名を解決するためのアンカーとなるパッケージの名前に設定する必要があります (例えばimport_module('..mod', 'pkg.subpkg')はpkg.modをインポートします)。import_module()関数はimportlib.__import__()を単純化するラッパーとして働きます。つまり、この関数のすべての意味はimportlib.__import__()から受け継いでいます。これらの2つの関数の最も重要な違いは、import_module()が指定されたパッケージやモジュール (例えばpkg.mod) を返すのに対し、__import__()はトップレベルのパッケージやモジュール (例えばpkg) を返すことです。もしモジュールを動的にインポートしていて、インタープリタの実行開始後にモジュールが作成された (例えば、 Python ソースファイルを作成した) 場合、インポートシステムが新しいモジュールを見つけられるように、
invalidate_caches()を呼ぶ必要があるでしょう。バージョン 3.3 で変更: 親パッケージは自動的にインポートされます。
- importlib.invalidate_caches()¶
sys.meta_pathに保存されたファインダーの内部キャッシュを無効にします。ファインダーがinvalidate_caches()を実装していれば、無効化を行うためにそれが呼び出されます。すべてのファインダーが新しいモジュールの存在に気づくことを保証しているプログラムの実行中に、モジュールが作成またはインストールされたなら、この関数が呼び出されるべきです。Added in version 3.3.
バージョン 3.10 で変更: Namespace packages created/installed in a different
sys.pathlocation after the same namespace was already imported are noticed.
- importlib.reload(module)¶
以前にインポートされた module をリロードします。引数はモジュールオブジェクトでなければならず、したがってそれ以前に必ずインポートに成功していなければなりません。この関数は、モジュールのソースファイルを外部エディタで編集していて Python インタープリタから離れることなく新しいバージョンを試したい際に便利です。戻り値はモジュールオブジェクトです。 (もし再インポートが異なるオブジェクトを
sys.modulesに配置したら、元の module とは異なるかもしれません。)reload()が実行された場合:Python モジュールのコードは再コンパイルされ、モジュールレベルのコードが再度実行されます。モジュールの辞書中にある何らかの名前に結び付けられたオブジェクトは、そのモジュールを最初にロードしたときの ローダー を再利用して新たに定義されます。拡張モジュールの
init関数が二度呼び出されることはありません。Python における他のオブジェクトと同様、以前のオブジェクトのメモリ領域は、参照カウントがゼロにならないかぎり再利用されません。
モジュール名前空間内の名前は新しいオブジェクト (または更新されたオブジェクト) を指すよう更新されます。
以前のオブジェクトが (外部の他のモジュールなどからの) 参照を受けている場合、それらを新たなオブジェクトに再束縛し直すことはないので、必要なら自分で名前空間を更新しなければなりません。
いくつか補足説明があります:
モジュールが再ロードされた際、その辞書 (モジュールのグローバル変数を含みます) はそのまま残ります。名前の再定義を行うと、以前の定義を上書きするので、一般的には問題はありません。新たなバージョンのモジュールが古いバージョンで定義された名前を定義していない場合、古い定義がそのまま残ります。辞書がグローバルテーブルやオブジェクトのキャッシュを維持していれば、この機能をモジュールを有効性を引き出すために使うことができます --- つまり、
try文を使えば、必要に応じてテーブルがあるかどうかをテストし、その初期化を飛ばすことができます:try: cache except NameError: cache = {}
組み込みモジュールや動的にロードされるモジュールを再ロードすることは、一般的にそれほど便利ではありません。
sys,__main__,builtinsやその他重要なモジュールの再ロードはお勧め出来ません。多くの場合、拡張モジュールは 1 度以上初期化されるようには設計されておらず、再ロードされた場合には何らかの理由で失敗するかもしれません。一方のモジュールが
from...import... を使って、オブジェクトを他方のモジュールからインポートしているなら、他方のモジュールをreload()で呼び出しても、そのモジュールからインポートされたオブジェクトを再定義することはできません --- この問題を回避する一つの方法は、from文を再度実行することで、もう一つの方法はfrom文の代わりにimportと限定的な名前 (module.name) を使うことです。あるモジュールがクラスのインスタンスを生成している場合、そのクラスを定義しているモジュールの再ロードはそれらインスタンスのメソッド定義に影響しません --- それらは古いクラス定義を使い続けます。これは派生クラスの場合でも同じです。
Added in version 3.4.
バージョン 3.7 で変更: リロードされたモジュールの
ModuleSpecが欠けていたときはModuleNotFoundErrorが送出されます。警告
This function is not thread-safe. Calling it from multiple threads can result in unexpected behavior. It's recommended to use the
threading.Lockor other synchronization primitives for thread-safe module reloading.
importlib.abc -- インポートに関連する抽象基底クラス¶
ソースコード: Lib/importlib/abc.py
importlib.abc モジュールは、 import に使われるすべてのコア抽象基底クラス含みます。コア抽象基底クラスの実装を助けるために、コア抽象基底クラスのサブクラスもいくつか提供されています。
抽象基底クラス階層:
object
+-- MetaPathFinder
+-- PathEntryFinder
+-- Loader
+-- ResourceLoader --------+
+-- InspectLoader |
+-- ExecutionLoader --+
+-- FileLoader
+-- SourceLoader
- class importlib.abc.MetaPathFinder¶
meta path finder を表す抽象基底クラスです。
Added in version 3.3.
バージョン 3.10 で変更: No longer a subclass of
Finder.- 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,Noneis returned. When passed in,targetis 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.Added in version 3.4.
- invalidate_caches()¶
このファインダーで使われている内部キャッシュがあれば無効にするオプションのメソッドです。
sys.meta_path上のすべてのファインダーのキャッシュを無効化する際、importlib.invalidate_caches()によって使われます。バージョン 3.4 で変更: Returns
Nonewhen called instead ofNotImplemented.
- class importlib.abc.PathEntryFinder¶
path entry finder を表す抽象基底クラスです。
MetaPathFinderと似ているところがありますが、PathEntryFinderはimportlib.machinery.PathFinderが提供するパスに基づく import サブシステムの中でのみ使うことが意図されています。Added in version 3.3.
バージョン 3.10 で変更: No longer a subclass of
Finder.- find_spec(fullname, target=None)¶
指定されたモジュールに対応する スペック を検索する抽象メソッド。ファインダーは、割り当てられている パス・エントリー 内のモジュールだけを検索します。スペックが見つからなければ
Noneが返されます。targetは、渡されてきたならモジュールオブジェクトです。これはファインダーがどのようなスペックを返せばよいか推測するために使用します。具体的なPathEntryFindersを実装するためにはimportlib.util.spec_from_loader()が便利かもしれません。Added in version 3.4.
- invalidate_caches()¶
このファインダーで使われている内部キャッシュがあれば無効にするオプションのメソッドです。キャッシュされたすべてのファインダーの無効化する際、
importlib.machinery.PathFinder.invalidate_caches()によって使われます。
- class importlib.abc.Loader¶
loader の抽象基底クラスです。ローダーの厳密な定義は PEP 302 を参照してください。
リソースの読み出しをサポートさせたいローダーには、
importlib.resources.abc.ResourceReaderで指定されているget_resource_reader()メソッドを実装してください。バージョン 3.7 で変更: オプションの
get_resource_reader()メソッドが導入されました。- create_module(spec)¶
モジュールをインポートする際に使用されるモジュールオブジェクトを返すメソッド。このメソッドは
Noneを戻すことができ、その場合はデフォルトのモジュール作成のセマンティクスが適用されることを示します。Added in version 3.4.
バージョン 3.6 で変更:
exec_module()が定義されている場合は、このメソッドはオプションではなくなりました。
- exec_module(module)¶
モジュールがインポートまたはリロードされる際に、そのモジュールをモジュール自身の名前空間の中で実行する抽象的なメソッド。
exec_module()が呼ばれる時点で、モジュールはすでに初期設定されている必要があります。 このメソッドが存在するときは、create_module()の定義が必須です。Added in version 3.4.
バージョン 3.6 で変更:
create_module()の定義が必須となりました。
- load_module(fullname)¶
モジュールをロードするためのレガシーなメソッドです。モジュールがロードできなければ
ImportErrorを送出し、ロードできればロードされたモジュールを返します。If the requested module already exists in
sys.modules, that module should be used and reloaded. Otherwise the loader should create a new module and insert it intosys.modulesbefore any loading begins, to prevent recursion from the import. If the loader inserted a module and the load fails, it must be removed by the loader fromsys.modules; modules already insys.modulesbefore the loader began execution should be left alone.ローダーはモジュールにいくつかの属性を設定する必要があります。(なお、これらの属性には、モジュールがリロードされた際に変化するものがあります):
module.__cached__(deprecated)module.__package__(deprecated)module.__loader__(deprecated)
exec_module()が利用可能な場合、後方互換な機能が提供されます。バージョン 3.4 で変更: Raise
ImportErrorwhen called instead ofNotImplementedError. Functionality provided whenexec_module()is available.Deprecated since version 3.4, will be removed in version 3.15: モジュールをロードするための推奨される API は、
exec_module()(およびcreate_module()) です。ローダーはload_module()の代わりにそれを実装するべきです。exec_module()が実装されている場合、インポート機構はload_module()の他のすべての責任を肩代わりします。
- class importlib.abc.ResourceLoader¶
TraversableResources に取って代わられました
loader の抽象基底クラスで、ストレージバックエンドから任意のリソースをロードするオプションの PEP 302 プロトコルを実装します。
バージョン 3.7 で非推奨: This ABC is deprecated in favour of supporting resource loading through
importlib.resources.abc.TraversableResources.- abstractmethod get_data(path)¶
An abstract method to return the bytes for the data located at path. Loaders that have a file-like storage back-end that allows storing arbitrary data can implement this abstract method to give direct access to the data stored.
OSErroris to be raised if the path cannot be found. The path is expected to be constructed using a module's__file__attribute or an item from a package's__path__.バージョン 3.4 で変更:
NotImplementedErrorの代わりにOSErrorを送出します。
- class importlib.abc.InspectLoader¶
loader の抽象基底クラスで、ローダーがモジュールを検査するためのオプションの PEP 302 プロトコルを実装します。
- get_code(fullname)¶
モジュールの
codeオブジェクトを返すか、 (例えば組み込みモジュールの場合に) モジュールがコードオブジェクトを持たなければNoneを返します。要求されたモジュールをローダーが見つけられなかった場合はImportErrorを送出します。注釈
このメソッドにはデフォルト実装がありますが、とはいえパフォーマンスのために、可能ならばオーバライドしたほうが良いです。
バージョン 3.4 で変更: このメソッドはもはや抽象メソッドではなく、具象実装が提供されます。
- abstractmethod get_source(fullname)¶
モジュールのソースを返す抽象メソッドです。これは認識されたすべての行セパレータを
'\n'文字に変換し、 universal newlines を使ったテキスト文字列として返されます。利用できるソースがなければ (例えば組み込みモジュール)、Noneを返します。指定されたモジュールが見つからなければ、ImportErrorを送出します。バージョン 3.4 で変更:
NotImplementedErrorの代わりにImportErrorを送出します。
- is_package(fullname)¶
モジュールがパッケージであれば True を返し、そうでなければ False を返すオプションのメソッドです。 ローダー がモジュールを見つけられなかったなら
ImportErrorが送出されます。バージョン 3.4 で変更:
NotImplementedErrorの代わりにImportErrorを送出します。
- static source_to_code(data, path='<string>')¶
Python のソースからコードオブジェクトを作ります。
data 引数は
compile()関数がサポートするもの (すなわち文字列かバイト) なら何でも構いません。path 引数はソースコードの元々の場所への "パス" でなければなりませんが、抽象概念 (例えば zip ファイル内の場所) でも構いません。結果のコードオブジェクトを使って、
exec(code, module.__dict__)を呼ぶことでモジュール内でコードを実行できます。Added in version 3.4.
バージョン 3.5 で変更: スタティックメソッドになりました。
- exec_module(module)¶
Loader.exec_module()の実装です。Added in version 3.4.
- load_module(fullname)¶
Loader.load_module()の実装です。Deprecated since version 3.4, will be removed in version 3.15: 代わりに
exec_module()を使用してください。
- class importlib.abc.ExecutionLoader¶
InspectLoaderから継承された抽象基底クラスで、実装されていれば、モジュールをスクリプトとして実行する助けになります。この抽象基底クラスはオプションの PEP 302 プロトコルを表します。- abstractmethod get_filename(fullname)¶
An abstract method that is to return the value of
__file__for the specified module. If no path is available,ImportErroris raised.ソースコードが利用できるなら、そのモジュールのロードにバイトコードが使われたかにかかわらず、このメソッドはそのソースファイルへのパスを返す必要があります。
バージョン 3.4 で変更:
NotImplementedErrorの代わりにImportErrorを送出します。
- class importlib.abc.FileLoader(fullname, path)¶
ResourceLoaderとExecutionLoaderから継承された抽象基底クラスで、ResourceLoader.get_data()およびExecutionLoader.get_filename()の具象実装を提供します。fullname 引数は、ローダーが解決しようとするモジュールの、完全に解決された名前です。path 引数は、モジュールのファイルへのパスです。
Added in version 3.3.
- name¶
ローダーが扱えるモジュールの名前です。
- path¶
モジュールのファイルへのパスです。
- load_module(fullname)¶
親クラスの
load_module()を呼び出します。Deprecated since version 3.4, will be removed in version 3.15: 代わりに
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が送出されます。Added in version 3.3.
バージョン 3.4 で変更:
NotImplementedErrorの代わりにOSErrorを送出します。
- path_mtime(path)¶
指定されたパスの更新時刻を返す、オプションの抽象メソッドです。
バージョン 3.3 で非推奨: このメソッドは廃止され、
path_stats()が推奨されます。このモジュールを実装する必要はありませんが、互換性のため現在も利用できます。パスが扱えなければ、OSErrorが送出されます。バージョン 3.4 で変更:
NotImplementedErrorの代わりにOSErrorを送出します。
- set_data(path, data)¶
ファイルパスに指定されたバイト列を書き込むオプションの抽象メソッドです。存在しない中間ディレクトリがあれば、自動で作成されます。
When writing to the path fails because the path is read-only (
errno.EACCES/PermissionError), do not propagate the exception.バージョン 3.4 で変更: 呼ばれたときに
NotImplementedErrorを送出することは最早ありません。
- get_code(fullname)¶
InspectLoader.get_code()の具象実装です。
- exec_module(module)¶
Loader.exec_module()の具象実装です。Added in version 3.4.
- load_module(fullname)¶
Loader.load_module()の具象実装です。Deprecated since version 3.4, will be removed in version 3.15: 代わりに
exec_module()を使用してください。
- get_source(fullname)¶
InspectLoader.get_source()の具象実装です。
- is_package(fullname)¶
InspectLoader.is_package()の具象実装です。モジュールは、次の 両方 を満たすならパッケージであると決定されます。モジュールの (ExecutionLoader.get_filename()で与えられる) ファイルパスが、ファイル拡張子を除くと__init__という名のファイルであること。モジュール名自体が__init__で終わらないこと。
- class importlib.abc.ResourceReader¶
TraversableResources に取って代わられました
resources の読み出し機能を提供する 抽象基底クラス (abstract base class, ABC) です。
From the perspective of this ABC, a resource is a binary artifact that is shipped within a package. Typically this is something like a data file that lives next to the
__init__.pyfile of the package. The purpose of this class is to help abstract out the accessing of such data files so that it does not matter if the package and its data file(s) are stored e.g. in a zip file versus on the file system.For any of methods of this class, a resource argument is expected to be a path-like object which represents conceptually just a file name. This means that no subdirectory paths should be included in the resource argument. This is because the location of the package the reader is for, acts as the "directory". Hence the metaphor for directories and file names is packages and resources, respectively. This is also why instances of this class are expected to directly correlate to a specific package (instead of potentially representing multiple packages or a module).
Loaders that wish to support resource reading are expected to provide a method called
get_resource_reader(fullname)which returns an object implementing this ABC's interface. If the module specified by fullname is not a package, this method should returnNone. An object compatible with this ABC should only be returned when the specified module is a package.Added in version 3.7.
Deprecated since version 3.12, will be removed in version 3.14: Use
importlib.resources.abc.TraversableResourcesinstead.- abstractmethod open_resource(resource)¶
Returns an opened, file-like object for binary reading of the resource.
リソースが見付からない場合は、
FileNotFoundErrorが送出されます。
- abstractmethod resource_path(resource)¶
resource へのファイルシステムパスを返します。
リソースの実体がファイルシステムに存在しない場合、
FileNotFoundErrorが送出されます。
- abstractmethod is_resource(name)¶
name という名前がリソースだと見なせるなら
Trueを返します。 name が存在しない場合はFileNotFoundErrorが送出されます。
- abstractmethod contents()¶
Returns an iterable of strings over the contents of the package. Do note that it is not required that all names returned by the iterator be actual resources, e.g. it is acceptable to return names for which
is_resource()would be false.Allowing non-resource names to be returned is to allow for situations where how a package and its resources are stored are known a priori and the non-resource names would be useful. For instance, returning subdirectory names is allowed so that when it is known that the package and resources are stored on the file system then those subdirectory names can be used directly.
The abstract method returns an iterable of no items.
- class importlib.abc.Traversable¶
An object with a subset of
pathlib.Pathmethods suitable for traversing directories and opening files.For a representation of the object on the file-system, use
importlib.resources.as_file().Added in version 3.9.
Deprecated since version 3.12, will be removed in version 3.14: Use
importlib.resources.abc.Traversableinstead.- name¶
Abstract. The base name of this object without any parent references.
- abstractmethod iterdir()¶
Yield
Traversableobjects inself.
- abstractmethod is_dir()¶
Return
Trueifselfis a directory.
- abstractmethod is_file()¶
Return
Trueifselfis a file.
- abstractmethod joinpath(child)¶
Return Traversable child in
self.
- abstractmethod __truediv__(child)¶
Return
Traversablechild inself.
- abstractmethod open(mode='r', *args, **kwargs)¶
mode may be 'r' or 'rb' to open as text or binary. Return a handle suitable for reading (same as
pathlib.Path.open).When opening as text, accepts encoding parameters such as those accepted by
io.TextIOWrapper.
- read_bytes()¶
Read contents of
selfas bytes.
- read_text(encoding=None)¶
Read contents of
selfas text.
- class importlib.abc.TraversableResources¶
An abstract base class for resource readers capable of serving the
importlib.resources.files()interface. Subclassesimportlib.resources.abc.ResourceReaderand provides concrete implementations of theimportlib.resources.abc.ResourceReader's abstract methods. Therefore, any loader supplyingimportlib.abc.TraversableResourcesalso supplies ResourceReader.Loaders that wish to support resource reading are expected to implement this interface.
Added in version 3.9.
Deprecated since version 3.12, will be removed in version 3.14: Use
importlib.resources.abc.TraversableResourcesinstead.- abstractmethod files()¶
Returns a
importlib.resources.abc.Traversableobject for the loaded package.
importlib.machinery -- インポータおよびパスフック¶
ソースコード: Lib/importlib/machinery.py
このモジュールには、 import がモジュールを検索してロードするのに役立つ様々なオブジェクトがあります。
- importlib.machinery.SOURCE_SUFFIXES¶
認識されているソースモジュールのファイル接尾辞を表す文字列のリストです。
Added in version 3.3.
- importlib.machinery.DEBUG_BYTECODE_SUFFIXES¶
最適化されていないバイトコードモジュールのファイル接尾辞を表す文字列のリストです。
Added in version 3.3.
バージョン 3.5 で非推奨: Use
BYTECODE_SUFFIXESinstead.
- importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES¶
最適化されたバイトコードモジュールのファイル接尾辞を表す文字列のリストです。
Added in version 3.3.
バージョン 3.5 で非推奨: Use
BYTECODE_SUFFIXESinstead.
- importlib.machinery.BYTECODE_SUFFIXES¶
認識されているバイトコードモジュールのファイル接尾辞を表す文字列のリストです (先頭のドットを含みます)。
Added in version 3.3.
バージョン 3.5 で変更: この値は
__debug__に依存しなくなりました。
- importlib.machinery.EXTENSION_SUFFIXES¶
認識されている最適化された拡張モジュールのファイル接尾辞を表す文字列のリストです。
Added in version 3.3.
- importlib.machinery.all_suffixes()¶
標準のインポート機構によって認識されているすべてのファイル接尾辞を表す文字列の組み合わせられたリストを返します。これが役立つのは、あるファイルシステムパスがモジュールを参照する可能性があるかだけを知りたくて、そのモジュールの種類を詳しく知る必要はないコード (例えば
inspect.getmodulename()) です。Added in version 3.3.
- class importlib.machinery.BuiltinImporter¶
組み込みモジュールの importer です。すべての既知のモジュールは
sys.builtin_module_namesに列挙されています。このクラスはimportlib.abc.MetaPathFinderおよびimportlib.abc.InspectLoader抽象基底クラスを実装します。インスタンス化の必要性を軽減するため、このクラスにはクラスメソッドだけが定義されています。
バージョン 3.5 で変更: PEP 489 の一環として、ビルトインインポーターは
Loader.create_module()とLoader.exec_module()を実装しています。
- class importlib.machinery.FrozenImporter¶
フリーズされたモジュールの インポーター です。このクラスは
importlib.abc.MetaPathFinderおよびimportlib.abc.InspectLoader抽象基底クラスを実装します。インスタンス化の必要性を軽減するため、このクラスにはクラスメソッドだけが定義されています。
バージョン 3.4 で変更: Gained
create_module()andexec_module()methods.
- class importlib.machinery.WindowsRegistryFinder¶
Windows レジストリで宣言されたモジュールの finder です。このクラスは
importlib.abc.MetaPathFinder抽象基底クラスを実装します。インスタンス化の必要性を軽減するため、このクラスにはクラスメソッドだけが定義されています。
Added in version 3.3.
バージョン 3.6 で非推奨: 代わりに
siteの設定を使ってください。 Python の将来のバージョンでは、デフォルトでこのファインダーが使えなくなるかもしれません。
- class importlib.machinery.PathFinder¶
sys.pathおよびパッケージの__path__属性の Finder です。このクラスはimportlib.abc.MetaPathFinder抽象基底クラスを実装します。インスタンス化の必要性を軽減するため、このクラスにはクラスメソッドだけが定義されています。
- classmethod find_spec(fullname, path=None, target=None)¶
sys.pathまたは定義されていれば path から、 fullname で指定されたモジュールの スペック の検索を試みるクラスメソッドです。検索されるそれぞれのパスエントリに対してsys.path_importer_cacheが検査されます。偽でないオブジェクトが見つかれば、それが目的のモジュールを検索するための パスエントリ・ファインダー として使われます。sys.path_importer_cacheに目的のエントリが見つからなければ、パスエントリに対するファインダーがsys.path_hooksから検索され、見つかれば、それがsys.path_importer_cacheに保管されるとともに、モジュールについて問い合わせられます。それでもファインダーが見つからなければNoneが保管され、また返されます。Added in version 3.4.
バージョン 3.5 で変更: もしカレントワーキングディレクトリ -- 空の文字列によって表されている -- がすでに有効でなければ、
Noneが返されますが値はsys.path_importer_cacheにキャッシュされません。
- classmethod invalidate_caches()¶
Calls
importlib.abc.PathEntryFinder.invalidate_caches()on all finders stored insys.path_importer_cachethat define the method. Otherwise entries insys.path_importer_cacheset toNoneare deleted.バージョン 3.7 で変更: Entries of
Noneinsys.path_importer_cacheare deleted.
バージョン 3.4 で変更:
''(すなわち空の文字列) に対してはカレントワーキングディレクトリとともにsys.path_hooksのオブジェクトを呼び出します。
- class importlib.machinery.FileFinder(path, *loader_details)¶
ファイルシステムからの結果をキャッシュする
importlib.abc.PathEntryFinderの具象実装です。path 引数は検索を担当するファインダーのディレクトリです。
loader_details 引数は、可変個の 2 要素タプルで、それぞれがローダーとローダーが認識するファイル接尾辞のシーケンスとを含みます。ローダーは、呼び出し可能でモジュール名と見つかったファイルのパスとの 2 引数を受け付けることを期待されます。
ファインダーはモジュール検索のたびに stat を呼び出し、必要に応じてディレクトリの内容をキャッシュすることで、コードキャッシュが古くなっていないことを確かめます。キャッシュの古さはオペレーティングシステムのファイルシステムのステート情報の粒度に依存しますから、モジュールを検索し、新しいファイルを作成し、その後に新しいファイルが表すモジュールを検索する、という競合状態の可能性があります。この操作が stat の呼び出しの粒度に収まるほど速く起こると、モジュールの検索が失敗します。これを防ぐためには、モジュールを動的に作成する際に、必ず
importlib.invalidate_caches()を呼び出してください。Added in version 3.3.
- path¶
ファインダーが検索されるパスです。
- invalidate_caches()¶
内部キャッシュを完全に消去します。
- classmethod path_hook(*loader_details)¶
A class method which returns a closure for use on
sys.path_hooks. An instance ofFileFinderis returned by the closure using the path argument given to the closure directly and loader_details indirectly.クロージャへの引数が存在するディレクトリでなければ、
ImportErrorが送出されます。
- class importlib.machinery.SourceFileLoader(fullname, path)¶
importlib.abc.FileLoaderを継承し、その他いくつかのメソッドの具象実装を提供する、importlib.abc.SourceLoaderの具象実装です。Added in version 3.3.
- name¶
このローダーが扱うモジュールの名前です。
- path¶
ソースファイルへのパスです。
- path_stats(path)¶
- set_data(path, data)¶
- load_module(name=None)¶
ロードするモジュールの名前指定がオプションの、
importlib.abc.Loader.load_module()の具象実装です。Deprecated since version 3.6, will be removed in version 3.15: 代わりに
importlib.abc.Loader.exec_module()を使用してください。
- class importlib.machinery.SourcelessFileLoader(fullname, path)¶
バイトコードファイル (すなわちソースコードファイルが存在しない) をインポートできる
importlib.abc.FileLoaderの具象実装です。注意として、バイトコードを直接使う (つまりソースコードファイルがない) と、そのモジュールはすべての Python 実装では使用できないし、新しいバージョンの Python ではバイトコードフォーマットが変更されていたら使用できません。
Added in version 3.3.
- name¶
ローダーが扱うモジュールの名前です。
- path¶
バイトコードファイルへのパスです。
- get_source(fullname)¶
このローダーが使われたとき、バイトコードファイルのソースがなければ
Noneを返します。
- load_module(name=None)¶
ロードするモジュールの名前指定がオプションの、
importlib.abc.Loader.load_module()の具象実装です。Deprecated since version 3.6, will be removed in version 3.15: 代わりに
importlib.abc.Loader.exec_module()を使用してください。
- class importlib.machinery.ExtensionFileLoader(fullname, path)¶
拡張モジュールのための
importlib.abc.ExecutionLoaderの具象実装です。fullname 引数はローダーがサポートするモジュールの名前を指定します。path 引数は拡張モジュールのファイルへのパスです。
Note that, by default, importing an extension module will fail in subinterpreters if it doesn't implement multi-phase init (see PEP 489), even if it would otherwise import successfully.
Added in version 3.3.
バージョン 3.12 で変更: Multi-phase init is now required for use in subinterpreters.
- name¶
ローダーがサポートするモジュールの名前です。
- path¶
拡張モジュールへのパスです。
- is_package(fullname)¶
Returns
Trueif the file path points to a package's__init__module based onEXTENSION_SUFFIXES.
- get_code(fullname)¶
拡張モジュールにコードオブジェクトがなければ
Noneを返します。
- get_source(fullname)¶
拡張モジュールにソースコードがなければ
Noneを返します。
- class importlib.machinery.NamespaceLoader(name, path, path_finder)¶
A concrete implementation of
importlib.abc.InspectLoaderfor namespace packages. This is an alias for a private class and is only made public for introspecting the__loader__attribute on namespace packages:>>> from importlib.machinery import NamespaceLoader >>> import my_namespace >>> isinstance(my_namespace.__loader__, NamespaceLoader) True >>> import importlib.abc >>> isinstance(my_namespace.__loader__, importlib.abc.Loader) True
Added in version 3.11.
- 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. Many of these attributes are also available directly on a module: for example,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. For example, it is possible to update the module's__file__at runtime and this will not be automatically reflected in the module's__spec__.origin, and vice versa.Added in version 3.4.
- name¶
The module's fully qualified name (see
module.__name__). The finder should always set this attribute to a non-empty string.
- loader¶
The loader used to load the module (see
module.__loader__). The finder should always set this attribute.
- origin¶
The location the loader should use to load the module (see
module.__file__). For example, for modules loaded from a.pyfile this is the filename. The finder should always set this attribute to a meaningful value for the loader to use. In the uncommon case that there is not one (like for namespace packages), it should be set toNone.
- submodule_search_locations¶
A (possibly empty) sequence of strings enumerating the locations in which a package's submodules will be found (see
module.__path__). Most of the time there will only be a single directory in this list.The finder should set this attribute to a sequence, even an empty one, to indicate to the import system that the module is a package. It should be set to
Nonefor non-package modules. It is set automatically later to a special object for namespace packages.
- loader_state¶
The finder may set this attribute to an object containing additional, module-specific data to use when loading the module. Otherwise it should be set to
None.
- cached¶
The filename of a compiled version of the module's code (see
module.__cached__). The finder should always set this attribute but it may beNonefor modules that do not need compiled code stored.
- parent¶
(Read-only) The fully qualified name of the package the module is in (or the empty string for a top-level module). See
module.__package__. If the module is a package then this is the same asname.
- class importlib.machinery.AppleFrameworkLoader(name, path)¶
フレームワーク形式の拡張モジュールを読み込み事ができる、特殊な
importlib.machinery.ExtensionFileLoaderです。iOS App Store との互換性のため、 iOS アプリの すべての バイナリモジュールは、パッケージ化されたアプリの
Frameworksフォルダーに保存された、適切なメタデータ付きのフレームワークにある動的ライブラリである必要があります。フレームワークごとにバイナリは一つだけで、 Frameworks フォルダーの外に実行可能バイナリデータを設置することはできません。To accommodate this requirement, when running on iOS, extension module binaries are not packaged as
.sofiles onsys.path, but as individual standalone frameworks. To discover those frameworks, this loader is registered against the.fworkfile extension, with a.fworkfile acting as a placeholder in the original location of the binary onsys.path. The.fworkfile contains the path of the actual binary in theFrameworksfolder, relative to the app bundle. To allow for resolving a framework-packaged binary back to the original location, the framework is expected to contain a.originfile that contains the location of the.fworkfile, relative to the app bundle.例えば、
from foo.bar import _whizをインポートする場合を考えてみましょう。_whizがバイナリモジュールsources/foo/bar/_whiz.abi3.soで実装されており、sourcesのアプリケーションバンドルからの相対パスがsys.pathに登録されています。このモジュールはFrameworks/foo.bar._whiz.framework/foo.bar._whiz(フレームワーク名はモジュールの完全なインポートパスから命名されています) として、バイナリをフレームワークとして識別するInfo.plistファイルを.frameworkディレクトリ内に設置して配布しなければなりません。foo.bar._whizモジュールは、元の場所で、Frameworks/foo.bar._whiz/foo.bar._whizのパスを含むsources/foo/bar/_whiz.abi3.fworkマーカーファイルに記述されます。 また、フレームワークは、.fworkへのパスを含むFrameworks/foo.bar._whiz.framework/foo.bar._whiz.originも含まなければなりません。When a module is loaded with this loader, the
__file__for the module will report as the location of the.fworkfile. This allows code to use the__file__of a module as an anchor for file system traveral. However, the spec origin will reference the location of the actual binary in the.frameworkfolder.The Xcode project building the app is responsible for converting any
.sofiles from wherever they exist in thePYTHONPATHinto frameworks in theFrameworksfolder (including stripping extensions from the module file, the addition of framework metadata, and signing the resulting framework), and creating the.fworkand.originfiles. This will usually be done with a build step in the Xcode project; see the iOS documentation for details on how to construct this build step.Added in version 3.13.
Availability: iOS.
- name¶
ローダーがサポートするモジュールの名前です。
- path¶
拡張モジュールの
.fworkファイルへのパス。
importlib.util -- インポータのためのユーティリティコード¶
ソースコード: Lib/importlib/util.py
このモジュールには、 インポーター の構築を助ける様々なオブジェクトがあります。
- importlib.util.MAGIC_NUMBER¶
バイトコードバージョン番号を表しているバイト列。バイトコードのロード/書き込みについてヘルプが必要なら
importlib.abc.SourceLoaderを参照してください。Added in version 3.4.
- importlib.util.cache_from_source(path, debug_override=None, *, optimization=None)¶
ソース path に関連付けられたバイトコンパイルされたファイルの PEP 3147/PEP 488 パスを返します。例えば、 path が
/foo/bar/baz.pyなら、 Python 3.2 の場合返り値は/foo/bar/__pycache__/baz.cpython-32.pycになります。cpython-32という文字列は、現在のマジックタグから得られます (マジックタグについてはget_tag()を参照;sys.implementation.cache_tagが未定義ならNotImplementedErrorが送出されます。)optimization パラメータは、バイトコードファイルの最適化レベルを指定するために使われます。空文字列は最適化しないことを表します。したがって、 optimization が
''のとき/foo/bar/baz.pyに対して/foo/bar/__pycache__/baz.cpython-32.pycというバイトコードパスが返ります。Noneにするとインタープリタの最適化レベルが使われます。それ以外では値の文字列表現が使われます。したがって、 optimization が2のとき/foo/bar/baz.pyに対して/foo/bar/__pycache__/baz.cpython-32.opt-2.pycというバイトコードパスが返ります。 optimization の文字列表現は英数字だけが可能で、そうでなければValueErrorが上げられます。debug_override パラメータは deprecated で、システムの
__debug__値をオーバーライドするために使用できます。True値は optimization を空文字列に設定するのと等価です。False値は optimization を1に設定するのと同等です。もし debug_override と optimization のどちらもNone以外であればTypeErrorが上げられます。Added in version 3.4.
バージョン 3.5 で変更: optimization パラメータが追加され、 debug_override パラメータは deprecated になりました。
バージョン 3.6 で変更: path-like object を受け入れるようになりました。
- importlib.util.source_from_cache(path)¶
PEP 3147 ファイル名への path が与えられると、関連するソースコードのファイルパスを返します。例えば、 path が
/foo/bar/__pycache__/baz.cpython-32.pycなら、返されるパスは/foo/bar/baz.pyになります。 path は存在する必要はありませんが、 PEP 3147 または PEP 488 フォーマットに一致しない場合はValueErrorが送出されます。sys.implementation.cache_tagが定義されていない場合、NotImplementedErrorが送出されます。Added in version 3.4.
バージョン 3.6 で変更: path-like object を受け入れるようになりました。
- importlib.util.decode_source(source_bytes)¶
与えられたソースコードを表すバイト列をデコードして、文字列としてそれを一般的な改行形式 (universal newlines) で返します (
importlib.abc.InspectLoader.get_source()で要求されるように)。Added in version 3.4.
- importlib.util.resolve_name(name, package)¶
相対的なモジュール名を解決して絶対的なものにします。
name の先頭にドットがなければ、単に name が返されます。これにより、例えば
importlib.util.resolve_name('sys', __spec__.parent)を使うときに package 変数が必要かどうかを確認する必要がなくなります。name が相対的なモジュール名であるにもかかわらず package が偽値 (例えば
Noneや空文字列) ならば、ImportErrorが送出されます。相対的な名前がそれを含むパッケージから抜け出る (例えばspamパッケージ内から..baconを要求する) 場合にもImportErrorが送出されます。Added in version 3.3.
バージョン 3.9 で変更: To improve consistency with import statements, raise
ImportErrorinstead ofValueErrorfor 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 beNoneor is not set, in which caseValueErroris raised). Otherwise a search usingsys.meta_pathis done.Noneis returned if no spec is found.name がサブモジュールを示している (ドットを含む) 場合、親モジュールは自動的にインポートされます。
name と package は
import_module()に対するものと同じように機能します。Added in version 3.4.
バージョン 3.7 で変更: Raises
ModuleNotFoundErrorinstead ofAttributeErrorif package is in fact not a package (i.e. lacks a__path__attribute).
- importlib.util.module_from_spec(spec)¶
spec と
spec.loader.create_moduleに基づいて新しいモジュールを作ります。spec.loader.create_moduleがNoneを返さない場合は、既に存在するどの属性もリセットされません。また、 spec にアクセスしたり属性をモジュールに設定したりする際にAttributeError例外が起きても例外は送出されません。この関数は、新しいモジュールを作る方法として
types.ModuleTypeよりも推奨されます。なぜなら、できるだけ多くのインポートコントロールされた属性をモジュールに設定するために spec が使用されるからです。Added in version 3.5.
- importlib.util.spec_from_loader(name, loader, *, origin=None, is_package=None)¶
この関数は、スペックに不足している情報を埋めるために
ModuleSpecのような利用可能な loader API を使います。Added in version 3.4.
- importlib.util.spec_from_file_location(name, location, *, loader=None, submodule_search_locations=None)¶
ファイルへのパスにもとづいて
ModuleSpecインスタンスを生成するためのファクトリー関数。不足している情報は、ローダー API を利用してスペックから得られる情報と、モジュールがファイルベースであるという暗黙的な情報によって埋められます。Added in version 3.4.
バージョン 3.6 で変更: path-like object を受け入れるようになりました。
- importlib.util.source_hash(source_bytes)¶
Return the hash of source_bytes as bytes. A hash-based
.pycfile embeds thesource_hash()of the corresponding source file's contents in its header.Added in version 3.7.
- importlib.util._incompatible_extension_module_restrictions(*, disable_check)¶
A context manager that can temporarily skip the compatibility check for extension modules. By default the check is enabled and will fail when a single-phase init module is imported in a subinterpreter. It will also fail for a multi-phase init module that doesn't explicitly support a per-interpreter GIL, when imported in an interpreter with its own GIL.
Note that this function is meant to accommodate an unusual case; one which is likely to eventually go away. There's is a pretty good chance this is not what you were looking for.
You can get the same effect as this function by implementing the basic interface of multi-phase init (PEP 489) and lying about support for multiple interpreters (or per-interpreter GIL).
警告
Using this function to disable the check can lead to unexpected behavior and even crashes. It should only be used during extension module development.
Added in version 3.12.
- class importlib.util.LazyLoader(loader)¶
モジュールが属性アクセスできるようになるまで、モジュールのローダーの実行を遅延するクラス。
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 returnNoneor a type for which its__class__attribute can be mutated along with not using slots. Finally, modules which substitute the object placed intosys.moduleswill not work as there is no way to properly replace the module references throughout the interpreter safely;ValueErroris raised if such a substitution is detected.注釈
起動時間が重要なプロジェクトでは、もし決して使われないモジュールがあれば、このクラスを使ってモジュールをロードするコストを最小化できるかもしれません。スタートアップ時間が重要でないプロジェクトでは、遅延されたロードの際に発生して文脈の外で起こるエラーメッセージのため、このクラスの使用は 著しく 推奨されません。
Added in version 3.5.
バージョン 3.6 で変更: Began calling
create_module(), removing the compatibility warning forimportlib.machinery.BuiltinImporterandimportlib.machinery.ExtensionFileLoader.- classmethod factory(loader)¶
遅延ローダを生成する callable を返すクラスメソッド。これは、ローダーをインスタンスとしてではなくクラスとして渡すような状況において使われることを意図しています。
suffixes = importlib.machinery.SOURCE_SUFFIXES loader = importlib.machinery.SourceFileLoader lazy_loader = importlib.util.LazyLoader.factory(loader) finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
使用例¶
プログラムからのインポート¶
プログラムからモジュールをインポートするには、 importlib.import_module() を使ってください。
import importlib
itertools = importlib.import_module('itertools')
モジュールがインポートできるか確認する¶
インポートを実際に行わずに、あるモジュールがインポートできるかを知る必要がある場合は、 importlib.util.find_spec() を使ってください。
Note that if name is a submodule (contains a dot),
importlib.util.find_spec() will import the parent module.
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")
ソースファイルから直接インポートする¶
This recipe should be used with caution: it is an approximation of an import
statement where the file path is specified directly, rather than
sys.path being searched. Alternatives should first be considered first,
such as modifying sys.path when a proper module is required, or using
runpy.run_path() when the global namespace resulting from running a Python
file is appropriate.
To import a Python source file directly from a path, use the following recipe:
import importlib.util
import sys
def import_from_path(module_name, file_path):
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)
return module
# For illustrative purposes only (use of `json` is arbitrary).
import json
file_path = json.__file__
module_name = json.__name__
# Similar outcome as `import json`.
json = import_from_path(module_name, file_path)
Implementing lazy imports¶
The example below shows how to implement lazy imports:
>>> import importlib.util
>>> import sys
>>> def lazy_import(name):
... spec = importlib.util.find_spec(name)
... loader = importlib.util.LazyLoader(spec.loader)
... spec.loader = loader
... module = importlib.util.module_from_spec(spec)
... sys.modules[name] = module
... loader.exec_module(module)
... return module
...
>>> lazy_typing = lazy_import("typing")
>>> #lazy_typing is a real module object,
>>> #but it is not loaded in memory yet.
>>> lazy_typing.TYPE_CHECKING
False
インポーターのセットアップ¶
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():
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