Python パッケージ - package
Publish date: 2021-03-07
Last updated: 2021-03-07
Last updated: 2021-03-07
Pythonではモジュールを名前空間で管理するための方法としてパッケージが提供されています。
パッケージの概要
パッケージはディレクトリで構造化され、
各ディレクトリ内に__init__.pyを配置する事で表現されます。
package_a1
│ module_sample1.py
│ module_sample2.py
│ __init__.py
│
├─package_b1
│ │ module_sample1.py
│ │ module_sample2.py
│ │ __init__.py
│ │
│ └─package_c1
│ module_sample1.py
│ module_sample2.py
│ __init__.py
│
└─package_b2
module_sample1.py
module_sample2.py__init__.pyは空のファイル、あるいは、
各モジュールの初期化処理や、配下のモジュールのimport処理を行う場所になります。
# module_sample1.py
def a():
print("a")
if __name__ == "__main__":
a()# module_sample2.py
def b():
print("b")
if __name__ == "__main__":
b()# __init__.py
from . import module_sample1以下のように、ピリオド.で名前空間を区切りモジュールの読み込みを行える。
import package_a1
package_a1.module_sample1.a()
import package_a1.package_b1
package_a1.package_b1.module_sample1.a()
import package_a1.package_b1.package_c1
package_a1.package_b1.package_c1.module_sample1.a()__init__.pyに記載がないため、パッケージをインポートしただけだと、
module_sample2は使用可能とならない。
import package_a1
package_a1.module_sample2.b()
# => AttributeError: module 'package_a1' has no attribute 'module_sample2'
import package_a1.package_b1
package_a1.package_b1.module_sample2.b()
# => AttributeError: module 'package_a1.package_b1' has no attribute 'module_sample2'
import package_a1.package_b1.package_c1
package_a1.package_b1.package_c1.module_sample2.b()
# => AttributeError: module 'package_a1.package_b1.package_c1' has no attribute 'module_sample2'以下のように直接指定すれば、module_sample2.bが使用できる。
import package_a1.module_sample2
package_a1.module_sample2.b()
import package_a1.package_b1.module_sample2
package_a1.package_b1.module_sample2.b()
import package_a1.package_b1.package_c1.module_sample2
package_a1.package_b1.package_c1.module_sample2.b()__init__.py自体がない場合も、直接指定しないとモジュールは使えるようにならない。
import package_a1.package_b2
package_a1.package_b2.module_sample1.a()
#=> AttributeError: module 'package_a1.package_b2' has no attribute 'module_sample1'
import package_a1.package_b2.module_sample1
package_a1.package_b2.module_sample1.a()