0
1

More than 3 years have passed since last update.

Python3.6のパッケージングとモジュールについて

Posted at

パッケージ? モジュール?を作る必要があったが、Pythonの基本がわからずハマってしまったので備忘録として残しまます。

ひとまずパッケージとモジュールの違いがわからないが、実験から以下を得られた.

環境

  • Python3.6

条件

ディレクトリ構成

fisig/
  __init__.py    # 空のファイル
  converter/
    __init__.py
    base.py
    sound.py
    acc.py

sound.py


from .base import base_converter
class SoundConverter:
    def convert():
        base_converter()

importのパターン



def test_import():
    import abesig.converter
    abesig.converter.sound.SoundConverter()

    import abesig.converter.sound
    abesig.converter.sound.SoundConverter()

def test_NG():
    with pytest.raises(ModuleNotFoundError):
        import abesig.converter.sound.SoundConverter

def test_from_import():
    from abesig import converter
    converter.sound.SoundConverter()

    from abesig.converter import sound
    sound.SoundConverter()

    from abesig.converter.sound import SoundConverter
    SoundConverter()


つまり、以下のようにはできない。言われてみると経験からわかるが。パイソニックには説明ができない。。まだまだ未熟でした。


import abesig.converter.sound.SoundConver
SoundConver()

その2: エイリアスを使う場合

(パイソニスタはエイリアスをなんというのだろう)

fisig/converter/init.py

from .sound import SoundConverter

test_import.py


def test_ailias():
    import abesig.converter
    abesig.converter.SoundConverter()

    from abesig import converter
    converter.SoundConverter()

    from abesig.converter import SoundConverter
    SoundConverter()

余談

下の記事を読んで用語を整理

Python の init.py とは何なのか - Qiita
Python 3.3b1 の名前空間パッケージを試してみた — 清水川Web

  • モジュール = xxxx.py 1ファイルのこと.
  • パッケージ = 複数ファイルをまとめたもの
  • 名前空間 = 名前空間
  • from/import = あくまでもモジュールのインポート
    • つまりfrom --- import --- の末尾はモジュールをさす
    • モジュール(xxx.py)内のクラス/メソッドを使いたい時に使う
  • パッケージ < モジュール < クラス/メソッド
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1