"imp" — Access the "import" internals
*************************************

このモジュールは "import" 文を実装するために使われているメカニズムへの
インターフェイスを提供します。次の定数と関数が定義されています:

imp.get_magic()

   バイトコンパイルされたコードファイル(".pyc" ファイル)を認識するため
   に使われるマジック文字列値を返します。 (この値は Python の各バージ
   ョンで異なります。)

imp.get_suffixes()

   3要素のタプルのリストを返します。それぞれのタプルは特定の種類のモジ
   ュールを説明しています。各タプルは "(suffix, mode, type)" という形
   式です。ここで、 *suffix* は探すファイル名を作るためにモジュール名
   に追加する文字列です。そのファイルをオープンするために、 *mode* は
   組み込み "open()" 関数へ渡されるモード文字列です (これはテキストフ
   ァイル対しては "'r'" 、バイナリファイルに対しては "'rb'" となります
   )。 *type* はファイル型で、以下で説明する値 "PY_SOURCE",
   "PY_COMPILED" あるいは、 "C_EXTENSION" の一つを取ります。

imp.find_module(name[, path])

   モジュール *name* を見つけようとします。 *path* が省略されるか
   "None" ならば、 "sys.path" によって与えられるディレクトリ名のリスト
   が検索されます。しかし、最初にいくつか特別な場所を検索します。まず
   、所定の名前をもつ組み込みモジュール("C_BUILTIN")を見つけようとしま
   す。それから、フリーズされたモジュール("PY_FROZEN")、そしていくつか
   のシステムでは他の場所が同様に検索されます (Windowsでは、特定のファ
   イルを指すレジストリの中を見ます)。

   それ以外の場合、 *path* はディレクトリ名のリストでなければなりませ
   ん。上の "get_suffixes()" が返す拡張子のいずれかを伴ったファイルを
   各ディレクトリの中で検索します。リスト内の有効でない名前は黙って無
   視されます(しかし、すべてのリスト項目は文字列でなければなりません)
   。

   検索が成功すれば、戻り値は3要素のタプル "(file, pathname,
   description)" です:

   *file* is an open file object positioned at the beginning,
   *pathname* is the pathname of the file found, and *description* is
   a 3-element tuple as contained in the list returned by
   "get_suffixes()" describing the kind of module found.

   モジュールがファイルとして存在していなければ、返された *file* は
   "None" で、 *pathname* は空文字列、 *description* タプルはその拡張
   子とモードに対して空文字列を含みます。モジュール型は上の括弧の中に
   示されます。検索が失敗すれば、 "ImportError" が発生します。他の例外
   は引数または環境に問題があることを示唆します。

   モジュールがパッケージならば、 *file* は "None" で、 *pathname* は
   パッケージのパスで *description* タプルの最後の項目は
   "PKG_DIRECTORY" です。

   この関数は階層的なモジュール名(ドットを含む名前)を扱いません。
   *P.M* 、すなわちパッケージ *P* のサブモジュール *M* を見つけるため
   には、まず "find_module()" と "load_module()" を使用してパッケージ
   *P* を見つけてロードして、次に "P.__path__" を *path* 引数にして
   "find_module()" を呼び出してください。もし *P* 自体がドット付きの名
   前を持つ場合、このレシピを再帰的に適用してください。

imp.load_module(name, file, pathname, description)

   Load a module that was previously found by "find_module()" (or by
   an otherwise conducted search yielding compatible results).  This
   function does more than importing the module: if the module was
   already imported, it is equivalent to a "reload()"!  The *name*
   argument indicates the full module name (including the package
   name, if this is a submodule of a package).  The *file* argument is
   an open file, and *pathname* is the corresponding file name; these
   can be "None" and "''", respectively, when the module is a package
   or not being loaded from a file.  The *description* argument is a
   tuple, as would be returned by "get_suffixes()", describing what
   kind of module must be loaded.

   ロードが成功したならば、戻り値はモジュールオブジェクトです。そうで
   なければ、例外(たいていは "ImportError")が発生します。

   **重要:** *file* 引数が "None" でなければ、例外が発生した場合でも呼
   び出し側にはそれを閉じる責任があります。これを行うには、 "try" …
   "finally" 文を使うことが最も良いです。

imp.new_module(name)

   *name* という名前の新しい空モジュールオブジェクトを返します。このオ
   ブジェクトは "sys.modules" に挿入され *ません* 。

imp.lock_held()

   Return "True" if the import lock is currently held, else "False".
   On platforms without threads, always return "False".

   On platforms with threads, a thread executing an import holds an
   internal lock until the import is complete. This lock blocks other
   threads from doing an import until the original import completes,
   which in turn prevents other threads from seeing incomplete module
   objects constructed by the original thread while in the process of
   completing its import (and the imports, if any, triggered by that).

imp.acquire_lock()

   Acquire the interpreter’s import lock for the current thread.  This
   lock should be used by import hooks to ensure thread-safety when
   importing modules.

   一旦スレッドがインポートロックを取得したら、その同じスレッドはブロ
   ックされることなくそのロックを再度取得できます。スレッドはロックを
   取得するのと同じだけ解放しなければなりません。

   スレッドのないプラットホームではこの関数は何もしません。

   バージョン 2.3 で追加.

imp.release_lock()

   Release the interpreter’s import lock. On platforms without
   threads, this function does nothing.

   バージョン 2.3 で追加.

整数値をもつ次の定数はこのモジュールの中で定義されており、
"find_module()" の検索結果を表すために使われます。

imp.PY_SOURCE

   ソースファイルとしてモジュールが発見された。

imp.PY_COMPILED

   コンパイルされたコードオブジェクトファイルとしてモジュールが発見さ
   れた。

imp.C_EXTENSION

   動的にロード可能な共有ライブラリとしてモジュールが発見された。

imp.PKG_DIRECTORY

   パッケージディレクトリとしてモジュールが発見された。

imp.C_BUILTIN

   モジュールが組み込みモジュールとして発見された。

imp.PY_FROZEN

   The module was found as a frozen module (see "init_frozen()").

The following constant and functions are obsolete; their functionality
is available through "find_module()" or "load_module()". They are kept
around for backward compatibility:

imp.SEARCH_ERROR

   Unused.

imp.init_builtin(name)

   Initialize the built-in module called *name* and return its module
   object along with storing it in "sys.modules".  If the module was
   already initialized, it will be initialized *again*.  Re-
   initialization involves the copying of the built-in module’s
   "__dict__" from the cached module over the module’s entry in
   "sys.modules".  If there is no built-in module called *name*,
   "None" is returned.

imp.init_frozen(name)

   Initialize the frozen module called *name* and return its module
   object.  If the module was already initialized, it will be
   initialized *again*.  If there is no frozen module called *name*,
   "None" is returned.  (Frozen modules are modules written in Python
   whose compiled byte-code object is incorporated into a custom-built
   Python interpreter by Python’s **freeze** utility. See
   "Tools/freeze/" for now.)

imp.is_builtin(name)

   Return "1" if there is a built-in module called *name* which can be
   initialized again.  Return "-1" if there is a built-in module
   called *name* which cannot be initialized again (see
   "init_builtin()").  Return "0" if there is no built-in module
   called *name*.

imp.is_frozen(name)

   Return "True" if there is a frozen module (see "init_frozen()")
   called *name*, or "False" if there is no such module.

imp.load_compiled(name, pathname[, file])

   Load and initialize a module implemented as a byte-compiled code
   file and return its module object.  If the module was already
   initialized, it will be initialized *again*.  The *name* argument
   is used to create or access a module object.  The *pathname*
   argument points to the byte-compiled code file.  The *file*
   argument is the byte-compiled code file, open for reading in binary
   mode, from the beginning. It must currently be a real file object,
   not a user-defined class emulating a file.

imp.load_dynamic(name, pathname[, file])

   Load and initialize a module implemented as a dynamically loadable
   shared library and return its module object.  If the module was
   already initialized, it will be initialized *again*. Re-
   initialization involves copying the "__dict__" attribute of the
   cached instance of the module over the value used in the module
   cached in "sys.modules".  The *pathname* argument must point to the
   shared library.  The *name* argument is used to construct the name
   of the initialization function: an external C function called
   "initname()" in the shared library is called.  The optional *file*
   argument is ignored.  (Note: using shared libraries is highly
   system dependent, and not all systems support it.)

   **CPython implementation detail:** The import internals identify
   extension modules by filename, so doing "foo = load_dynamic("foo",
   "mod.so")" and "bar = load_dynamic("bar", "mod.so")" will result in
   both foo and bar referring to the same module, regardless of
   whether or not "mod.so" exports an "initbar" function. On systems
   which support them, symlinks can be used to import multiple modules
   from the same shared library, as each reference to the module will
   use a different file name.

imp.load_source(name, pathname[, file])

   Load and initialize a module implemented as a Python source file
   and return its module object.  If the module was already
   initialized, it will be initialized *again*.  The *name* argument
   is used to create or access a module object.  The *pathname*
   argument points to the source file.  The *file* argument is the
   source file, open for reading as text, from the beginning. It must
   currently be a real file object, not a user-defined class emulating
   a file.  Note that if a properly matching byte-compiled file (with
   suffix ".pyc" or ".pyo") exists, it will be used instead of parsing
   the given source file.

class imp.NullImporter(path_string)

   "NullImporter" 型は **PEP 302** インポートフックで、何もモジュール
   が見つからなかったときの非ディレクトリパス文字列を処理します。この
   型を既存のディレクトリや空文字列に対してコールすると "ImportError"
   が発生します。それ以外の場合は "NullImporter" のインスタンスが返さ
   れます。

   Python adds instances of this type to "sys.path_importer_cache" for
   any path entries that are not directories and are not handled by
   any other path hooks on "sys.path_hooks".  Instances have only one
   method:

   find_module(fullname[, path])

      このメソッドは常に "None" を返し、要求されたモジュールが見つから
      なかったことを表します。

   バージョン 2.5 で追加.


使用例
======

次の関数は Python 1.4 までの標準 import 文(階層的なモジュール名がない)
をエミュレートします。 (この *実装* はそのバージョンでは動作しないでし
ょう。なぜなら、 "find_module()" は拡張されており、また
"load_module()" が 1.4 で追加されているからです。)

   import imp
   import sys

   def __import__(name, globals=None, locals=None, fromlist=None):
       # Fast path: see if the module has already been imported.
       try:
           return sys.modules[name]
       except KeyError:
           pass

       # If any of the following calls raises an exception,
       # there's a problem we can't handle -- let the caller handle it.

       fp, pathname, description = imp.find_module(name)

       try:
           return imp.load_module(name, fp, pathname, description)
       finally:
           # Since we may exit via an exception, close fp explicitly.
           if fp:
               fp.close()

A more complete example that implements hierarchical module names and
includes a "reload()" function can be found in the module "knee".  The
"knee" module can be found in "Demo/imputil/" in the Python source
distribution.
