Python : モジュールとパッケージ

参考書籍 : Python実践入門


・モジュール
モジュールはコードを記述したpyファイルで、importされて使われる。
encoder.py

import base64


def str_to_base64(x: str):
    return base64.b64encode(x.encode('utf-8'))

別ファイルから呼び出す。

import encoder


print(type(encoder))  # <class 'module'>
print(dir(encoder))  # ['__builtins__', ... '__name__', '__package__', '__spec__', 'base64', 'str_to_base64']
print(encoder.str_to_base64('python'))  # b'cHl0aG9u'

import encoderをするとmoduleオブジェクトのインスタンスencoderが作成される。



・if __name__ == '__main__' について

import base64


def str_to_base64(x: str):
    return base64.b64encode(x.encode('utf-8'))


def main():
    print(str_to_base64('python'))


if __name__ == '__main__':
    main()

__name__の値は.pyファイルがどのように利用されるかで変わる。
スクリプトとして利用された場合、もしくは対話モードの場合の__name__は'__main__'になる。
importされた場合、__name__はインポートされたモジュール名になる。



・パッケージ
パッケージは、複数のモジュールをまとめたものである。
ディレクトリb64を作り、その中に__init__.py, encoder.py, decoder.pyを配置する。
__init__.pyは空のファイルとする。
encoder.py

import base64


def str_to_base64(x: str):
    return base64.b64encode(x.encode('utf-8'))

decoder.py

import base64


def base64_to_str(x):
    return base64.b64decode(x).decode('utf-8')

別ファイルから呼び出す。

from b64 import encoder, decoder


print(encoder.str_to_base64('python'))  # b'cHl0aG9u'
print(decoder.base64_to_str(b'cHl0aG9u'))  # python

b64がパッケージとなり、from b64でb64からimportできる。

ここで、__init__.pyを以下のように書き換える。

from .encoder import str_to_base64
from .decoder import base64_to_str

これにより、import b64だけでencoderとdecoderの関数が呼び出せる。

import b64


print(b64.str_to_base64('python'))  # b'cHl0aG9u'
print(b64.base64_to_str(b'cHl0aG9u'))  # python

また、モジュールの属性を直接インポートし、b64なしで呼び出すことができる。

from b64 import str_to_base64, base64_to_str


print(str_to_base64('python'))  # b'cHl0aG9u'
print(base64_to_str(b'cHl0aG9u'))  # python

asを使い、インポートしたオブジェクトに別名をつけられる。

from gzip import open as gzip_open

これにより、組み込み関数open()もgzipのopen()も使うことができる。