LoginSignup
494
470

More than 1 year has passed since last update.

Python 3でのファイルのimportのしかたまとめ

Last updated at Posted at 2016-07-05

同じディレクトリにあるファイル

.
├── brother.py
└── main.py
brother.py
def hi():
    print("Hi! I'm your brother.")
main.py
import brother
brother.hi()

ひとつ下のディレクトリにある個別のファイル

.
├── children
│   └── tom.py
└── main.py
tom.py
def hi():
    print("Hi! I'm Tom.")

いい例 1:

main.py
from children import tom
tom.hi()

いい例 2:

main.py
import children.tom
children.tom.hi()

だめな例: →パッケージにする必要がある(後述)

main.py
import children
children.tom.hi() # >> AttributeError: module 'children' has no attribute 'tom'

ひとつ下のディレクトリにある複数のファイル

__init__.pyを作り、そのディレクトリをパッケージとして扱う。__init__.pyの中でそこで同じディレクトリに含まれるモジュールを読み込む。

.
├── children
│   ├── __init__.py
│   ├── sushi.py
│   └── tom.py
└── main.py
sushi.py
def hi():
    print("Hi! I'm Sushi.")

いい例
モジュールの中では、.を使って相対パスで読み込むモジュールを指定する。(公式リリースノート参考)

__init__.py
from . import tom
from . import sushi
main.py
import children
children.sushi.hi()

△な例: こうすることもできる

__init__.py
from .tom import hi as tom_hi
from .sushi import hi as sushi_hi
main.py
from children import *
sushi_hi()

だめな例

__init__.py
import tom # >> ImportError: No module named 'tom'
import sushi

毎回モジュールを書き足すのが面倒な場合はここなどを参考に、同じディレクトリにあるファイルをすべて読み込むようにする。

ひとつ上のディレクトリにあるファイル

そもそもこういうことはあまりすべきではないかもしれないが、やりたいときもある。

.
├── children
│   └── main.py
└── mother.py
mother.py
def hi():
    print("Hi! I'm your mother.")

いい例 :
親ディレクトリをパスに含めた上でモジュールであるmother.pyを読み込む。

参考: Import From Parent Folder / Python Cook Book

main.py
from pathlib import Path
import sys
sys.path.append(str(Path(__file__).resolve().parent.parent))
import mother

mother.hi()

悪い例 :

main.py
from .. import mother # >> ImportError: attempted relative import with no known parent package

mother.hi()
494
470
1

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
494
470