
:mod:`imp` --- :keyword:`import` 内部へアクセスする
===================================================

.. module:: imp
   :synopsis: import文の実装へアクセスする。


.. index:: statement: import

.. This module provides an interface to the mechanisms used to implement the
.. :keyword:`import` statement.  It defines the following constants and functions:

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


.. function:: get_magic()

   .. index:: pair: file; byte-code

   .. Return the magic string value used to recognize byte-compiled code files
   .. (:file:`.pyc` files).  (This value may be different for each Python version.)

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


.. function:: get_suffixes()

   .. Return a list of 3-element tuples, each describing a particular type of
   .. module. Each triple has the form ``(suffix, mode, type)``, where *suffix* is
   .. a string to be appended to the module name to form the filename to search
   .. for, *mode* is the mode string to pass to the built-in :func:`open` function
   .. to open the file (this can be ``'r'`` for text files or ``'rb'`` for binary
   .. files), and *type* is the file type, which has one of the values
   .. :const:`PY_SOURCE`, :const:`PY_COMPILED`, or :const:`C_EXTENSION`, described
   .. below.

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


.. function:: find_module(name[, path])

   .. Try to find the module *name*.  If *path* is omitted or ``None``, the list of
   .. directory names given by ``sys.path`` is searched, but first a few special
   .. places are searched: the function tries to find a built-in module with the
   .. given name (:const:`C_BUILTIN`), then a frozen module (:const:`PY_FROZEN`),
   .. and on some systems some other places are looked in as well (on Windows, it
   .. looks in the registry which may point to a specific file).

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

   .. Otherwise, *path* must be a list of directory names; each directory is
   .. searched for files with any of the suffixes returned by :func:`get_suffixes`
   .. above.  Invalid names in the list are silently ignored (but all list items
   .. must be strings).

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


   .. If search is successful, the return value is a 3-element tuple ``(file,
   .. pathname, description)``:

   検索が成功すれば、戻り値は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 :func:`get_suffixes` describing the kind of
   .. module found.

   *file* は先頭に位置合わせされたオープンファイルオブジェクトで、 *pathname* は見つかったファイルのパス名です。
   そして、 *description* は :func:`get_suffixes` が返すリストに含まれているような3要素のタプルで、
   見つかったモジュールの種類を説明しています。


   .. If the module does not live in a file, the returned *file* is ``None``,
   .. *pathname* is the empty string, and the *description* tuple contains empty
   .. strings for its suffix and mode; the module type is indicated as given in
   .. parentheses above.  If the search is unsuccessful, :exc:`ImportError` is
   .. raised.  Other exceptions indicate problems with the arguments or
   .. environment.

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


   .. If the module is a package, *file* is ``None``, *pathname* is the package
   .. path and the last item in the *description* tuple is :const:`PKG_DIRECTORY`.

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


   .. This function does not handle hierarchical module names (names containing
   .. dots).  In order to find *P*.*M*, that is, submodule *M* of package *P*, use
   .. :func:`find_module` and :func:`load_module` to find and load package *P*, and
   .. then use :func:`find_module` with the *path* argument set to ``P.__path__``.
   .. When *P* itself has a dotted name, apply this recipe recursively.

   この関数は階層的なモジュール名(ドットを含んだ名前)を扱いません。
   *P.M* 、すなわち、パッケージ *P* のサブモジュール *M* を見つけるためには、
   パッケージ *P* を見つけてロードするために :func:`find_module` と :func:`load_module` を使い、
   それから ``P.__path__`` に設定された *path* 引数とともに :func:`find_module` を使ってください。
   *P* 自身がドット名のときは、このレシピを再帰的に適用してください。


.. function:: load_module(name, file, pathname, description)

   .. index:: builtin: reload

   .. Load a module that was previously found by :func:`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 :func:`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 :func:`get_suffixes`, describing
   .. what kind of module must be loaded.

   :func:`find_module` を使って(あるいは、互換性のある結果を作り出す検索を行って)以前見つけたモジュールをロードします。
   この関数はモジュールをインポートするという以上のことを行います:
   モジュールが既にインポートされているならば、 :func:`reload` と同じです!
   *name* 引数は(これがパッケージのサブモジュールならばパッケージ名を含む)完全なモジュール名を示します。
   *file* 引数はオープンしたファイルで、 *pathname* は対応するファイル名です。
   モジュールがパッケージであるかファイルからロードされようとしていないとき、これらはそれぞれ ``None`` と ``''`` であっても構いません。
   :func:`get_suffixes` が返すように *description* 引数はタプルで、どの種類のモジュールがロードされなければならないかを説明するものです。


   .. If the load is successful, the return value is the module object; otherwise,
   .. an exception (usually :exc:`ImportError`) is raised.

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


   .. **Important:** the caller is responsible for closing the *file* argument, if
   .. it was not ``None``, even when an exception is raised.  This is best done
   .. using a :keyword:`try` ... :keyword:`finally` statement.

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


.. function:: new_module(name)

   .. Return a new empty module object called *name*.  This object is *not* inserted
   .. in ``sys.modules``.

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


.. function:: lock_held()

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

   現在インポートロックが維持されているならば、 ``True`` を返します。そうでなければ、 ``False`` を返します。
   スレッドのないプラットホームでは、常に ``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).

   スレッドのあるプラットホームでは、インポートが完了するまでインポートを実行するスレッドは内部ロックを維持します。
   このロックは元のインポートが完了するまで他のスレッドがインポートすることを阻止します。
   言い換えると、元のスレッドがそのインポート(および、もしあるならば、それによって引き起こされるインポート)
   の途中で構築した不完全なモジュールオブジェクトを、他のスレッドが見られないようにします。


.. function:: 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.

   実行中のスレッドでインタープリタのインポートロックを取得します。
   インポートフックは、スレッドセーフのためにこのロックを取得しなければ
   なりません。

   .. Once a thread has acquired the import lock, the same thread may acquire it
   .. again without blocking; the thread must release it once for each time it has
   .. acquired it.

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


   .. On platforms without threads, this function does nothing.

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


   .. versionadded:: 2.3


.. function:: release_lock()

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

   インタープリタのインポートロックを解放します。
   スレッドのないプラットホームではこの関数は何もしません。


   .. versionadded:: 2.3


.. The following constants with integer values, defined in this module, are used to
.. indicate the search result of :func:`find_module`.

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


.. data:: PY_SOURCE

   .. The module was found as a source file.

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


.. data:: PY_COMPILED

   .. The module was found as a compiled code object file.

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


.. data:: C_EXTENSION

   .. The module was found as dynamically loadable shared library.

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


.. data:: PKG_DIRECTORY

   .. The module was found as a package directory.

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


.. data:: C_BUILTIN

   .. The module was found as a built-in module.

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


.. data:: PY_FROZEN

   .. The module was found as a frozen module (see :func:`init_frozen`).

   モジュールがフリーズされたモジュールとして発見された(:func:`init_frozen` を参照)。


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

以下の定数と関数は旧バージョンのものです。
:func:`find_module` や :func:`load_module` を使えば同様の機能を利用できます。
これらは後方互換性のために残されています:


.. data:: SEARCH_ERROR

   .. Unused.

   使われていません。


.. function:: 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.

   *name* という名前の組み込みモジュールを初期化し、そのモジュールオブジェクトを ``sys.modules`` に格納した上で返します。
   モジュールが既に初期化されている場合は、 *再度* 初期化されます。
   再初期化は組み込みモジュールの ``__dict__`` を ``sys.modules`` のエントリーに結びつけられたキャッシュモジュールからコピーする過程を含みます。
   *name* という名前の組み込みモジュールがない場合は、 ``None`` を返します。


.. function:: 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 :program:`freeze`
   .. utility. See :file:`Tools/freeze/` for now.)

   *name* という名前のフリーズされたモジュールを初期化し、モジュールオブジェクトを返します。
   モジュールが既に初期化されている場合は、 *再度* 初期化されます。
   *name* という名前のフリーズされたモジュールがない場合は、 ``None`` を返します。
   (フリーズされたモジュールは Python で書かれたモジュールで、そのコンパイルされたバイトコードオブジェクトが
   Python の :program:`freeze` ユーティリティを使ってカスタムビルド版の Python インタープリタへ組み込まれています。
   差し当たり、 :file:`Tools/freeze/` を参照してください。)


.. function:: 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 :func:`init_builtin`).  Return ``0`` if
   .. there is no built-in module called *name*.

   *name* という名前の再初期化できる組み込みモジュールがある場合は、 ``1`` を返します。
   *name* という名前の再初期化できない組み込みモジュールがある場合は、 ``-1`` を返します
   (:func:`init_builtin` を参照してください)。 *name* という名前の組み込みモジュールがない場合は、 ``0`` を返します。


.. function:: is_frozen(name)

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

   *name* という名前のフリーズされたモジュール(:func:`init_frozen` を参照)がある場合は、 ``True`` を返します。
   または、そのようなモジュールがない場合は、 ``False`` を返します。


.. function:: load_compiled(name, pathname[, file])

   .. index:: pair: file; byte-code

   .. 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.

   バイトコンパイルされたコードファイルとして実装されているモジュールをロードして初期化し、
   そのモジュールオブジェクトを返します。
   モジュールが既に初期化されている場合は、 *再度* 初期化されます。
   *name* 引数はモジュールオブジェクトを作ったり、アクセスするために使います。
   *pathname* 引数はバイトコンパイルされたコードファイルを指します。
   *file* 引数はバイトコンパイルされたコードファイルで、バイナリモードでオープンされ、先頭からアクセスされます。
   現在は、ユーザ定義のファイルをエミュレートするクラスではなく、実際のファイルオブジェクトでなければなりません。


.. function:: 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.)

   動的ロード可能な共有ライブラリとして実装されているモジュールをロードして初期化します。
   モジュールが既に初期化されている場合は、 *再度* 初期化します。
   再初期化はモジュールのキャッシュされたインスタンスの ``__dict__`` 属性を
   ``sys.modules`` にキャッシュされたモジュールの中で使われた値に上書きコピーする過程を含みます。
   *pathname* 引数は共有ライブラリを指していなければなりません。
   *name* 引数は初期化関数の名前を作るために使われます。
   共有ライブラリの ``initname()`` という名前の外部C関数が呼び出されます。
   オプションの *file* 引数は無視されます。
   (注意: 共有ライブラリはシステムに大きく依存します。
   また、すべてのシステムがサポートしているわけではありません。)


.. function:: 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 :file:`.pyc` or :file:`.pyo`)
   .. exists, it will be used instead of parsing the given source file.

   Python ソースファイルとして実装されているモジュールをロードして初期化し、モジュールオブジェクトを返します。
   モジュールが既に初期化されている場合は、 *再度* 初期化します。
   *name* 引数はモジュールオブジェクトを作成したり、アクセスしたりするために使われます。
   *pathname* 引数はソースファイルを指します。
   *file* 引数はソースファイルで、テキストとして読み込むためにオープンされ、先頭からアクセスされます。
   現在は、ユーザ定義のファイルをエミュレートするクラスではなく、実際のファイルオブジェクトでなければなりません。
   (拡張子 :file:`.pyc` または :file:`.pyo` をもつ)正しく対応するバイトコンパイルされたファイルが存在する場合は、
   与えられたソースファイルを構文解析する代わりにそれが使われることに注意してください。


.. class:: NullImporter(path_string)

   .. The :class:`NullImporter` type is a :pep:`302` import hook that handles
   .. non-directory path strings by failing to find any modules.  Calling this type
   .. with an existing directory or empty string raises :exc:`ImportError`.
   .. Otherwise, a :class:`NullImporter` instance is returned.

   :class:`NullImporter` 型は :pep:`302` インポートフックで、何もモジュールが見つからなかったときの
   非ディレクトリパス文字列を処理します。
   この型を既存のディレクトリや空文字列に対してコールすると :exc:`ImportError` が発生します。
   それ以外の場合は :class:`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:

   Python は、ディレクトリでなく ``sys.path_hooks`` のどのパスフックでも処理されていないすべてのパスエントリに対して、
   この型のインスタンスを ``sys.path_importer_cache`` に追加します。
   このインスタンスが持つメソッドは次のひとつです。


   .. method:: NullImporter.find_module(fullname [, path])

      .. This method always returns ``None``, indicating that the requested module could
      .. not be found.

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


   .. versionadded:: 2.5


.. _examples-imp:

例
--

.. The following function emulates what was the standard import statement up to
.. Python 1.4 (no hierarchical module names).  (This *implementation* wouldn't work
.. in that version, since :func:`find_module` has been extended and
.. :func:`load_module` has been added in 1.4.) :

次の関数は Python 1.4 までの標準 import 文(階層的なモジュール名がない)をエミュレートします。
(この *実装* はそのバージョンでは動作しないでしょう。なぜなら、 :func:`find_module` は拡張されており、
また :func:`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()


.. index::
   builtin: reload
   module: knee


.. A more complete example that implements hierarchical module names and includes a
.. :func:`reload` function can be found in the module :mod:`knee`.  The :mod:`knee`
.. module can be found in :file:`Demo/imputil/` in the Python source distribution.

階層的なモジュール名を実装し、 :func:`reload` 関数を含むより完全な例はモジュール :mod:`knee` にあります。
:mod:`knee` モジュールは Python のソースディストリビューションの中の :file:`Demo/imputil/` にあります。

