概要
モジュールは共通して利用したい実行ファイルをインポートできるように配置したもの。パッケージはパッケージやモジュールをひとまとめにするもの。
- ローカルの実行環境では、ディレクトリがパッケージになる
- パッケージ内の__init__.pyファイルは特別なモジュールで、パッケージをインポートするだけでモジュール内の関数やクラスが使える
- パッケージ下にモジュールファイルを置くと、
[パッケージ名].[モジュール名]でモジュール内の関数やクラスが使える
- パッケージのセットアップとインストール→今後
カレントディレクトリ下での使用
モジュールは普通のPython実行ファイルで作成。
たとえばカレントディレクトリに以下のようなファイルをtestmodule.pyとして置く。このモジュールには関数が1つとクラスが1つ定義されている。
|
1 2 3 4 5 6 7 8 |
# testmodule.py def exec(): print("Test module") class ModuleClass: def display(self): print("Module class") |
そして同じカレントディレクトリにあるtest.pyを以下のように書く。
|
1 2 3 4 5 6 7 8 |
# test.py import testmodule testmodule.exec() instance = testmodule.ModuleClass() instance.display() |
この時点でファイル構成は以下のようになっている。
|
1 2 3 |
<python> test.py testmodule.py |
ここでtest.pyを実行すると次のように表示される。無事インポートできて、モジュールで定義した関数、クラスとも使える。
|
1 2 |
Test module Module class |
実行後には新しいディレクトリが追加されて、以下のようになった。
|
1 2 3 4 5 |
<python> test.py testmodule.py <__pycache__> testmodule.cpython-35.pyc |
カレントディレクトリ下でのモジュール管理のまとめ
- 関数・クラスなどを含むモジュールをPythonファイルとして作成し、カレントファイルに置く
- 利用側で、モジュール名(モジュールのファイル名から拡張子”.py”を除いた名前)を指定してインポート
[モジュール名].[関数名/クラス名]として利用
サブディレクトリ管理でのエラー
モジュールをカレントディレクトリではなくサブディレクトリに置いて管理したいので、以下のように置いてみる。
|
1 2 3 4 |
<python> test.py <subdir> testmodule.py |
そして以下のように呼び出そうとしたが残念ながらエラー。
|
1 2 3 4 |
import subdir.testmodule # import subdir/testmodule # SyntaxError: invalid syntax |
ただしこの実行後、サブディレクトリの下に新しいディレクトリがつくられていた。
|
1 2 3 4 5 6 |
<python> test.py <subdir> testmodule.py <__pyckache__> testmodule.cpython-35.pyc |
これはimport文を読んだPythonがsubdirというパッケージを探しに行ったが見つからなかったためで、モジュールを置いたディレクトリをパッケージとしてPythonに認識させる必要がある。
パッケージ
パッケージ直下のモジュール
ディレクトリをパッケージとしてPythonに認識させるためには__init__.pyというファイルが必要になる。
たとえば以下のようなディレクトリ・ファイル構造として
|
1 2 3 4 |
<python> test.py <testpackage> __init__.py |
__init__.pyファイル内容を前のtestmodule.pyと同じとする。
|
1 2 3 4 5 6 7 8 |
# __init__.py def exec(): print("Test module") class ModuleClass: def display(self): print("Module class") |
カレントディレクトリ下のtest.pyでは前は[モジュール名].[関数/クラス]としていたが、今回は以下のようにパッケージから呼び出すように変更。__init__.pyファイルに書いたモジュールは、パッケージ直下から呼び出される。
|
1 2 3 4 5 6 7 8 |
# test.py import testpackage testpackage.exec() instance = testpackage.ModuleClass() instance.display() |
出力は以下の通りとなって成功。
|
1 2 |
Test module Module class |
またここでもmypackageディレクトリの下に新しいディレクトリが作成された。
|
1 2 3 4 5 6 |
<python> test.py <testpackage> __init__.py <pychache> __init__.cpython-35.pyc |
パッケージ内のモジュール
testpackageディレクトリ下にothermodule.pyファイルを置く。
|
1 2 3 4 5 |
<python> test.py <testpackage> __init__.py othermodule.py |
|
1 2 3 4 |
# othermodule.py def exec(): print("Other module") |
test.pyを以下のようにして実行。
|
1 2 3 4 5 6 7 8 9 10 11 |
# test.py import testpackage import testpackage.othermodule testpackage.exec() instance = testpackage.ModuleClass() instance.display() testpackage.othermodule.exec() |
以下のように実行される。
|
1 2 3 |
Test module Module class Other module |
一度実行されると、pycacheディレクトリに新たなファイルが追加される。
|
1 2 3 4 5 6 7 8 |
<python> test.py <testpackage> __init__.py othermodule.py <pychache> __init__.cpython-35.pyc othermodule.cpython-35.pyc |