LoginSignup
11
2

More than 3 years have passed since last update.

モジュールもオブジェクト、import文で変数に代入

Last updated at Posted at 2019-08-09

Pythonではモジュールもオブジェクトです。
Pythonインタープリタがimport文を見つけると、指定されたファイルをコンパイルしてmoduleオブジェクトを作り、変数に代入します。
関数の中にimport文を書くと、関数を呼ぶ度にimport処理してしまいます。モジュールはキャッシュされるので、2回目からはキャッシュされたモジュールが変数に代入されます。PEP8ではimport文をファイルの先頭にまとめて書くことを推奨しています。

以下のimport文は、

import math
import numpy as np
from random import choice
from random import randint as ri

Pythonインタープリタは以下のように解釈して実行します。
__import__は組込み関数 です。
※注意※: リンク先に書いてありますが、ユーザプログラムではimportlib.import_module()を使いましょう。

math = __import__('math')
np = __import__('numpy')
choice = __import__('random').choice
ri = __import__('random').randint

vars() で変数辞書を確認してみます。

実験
>>> import math
>>> vars()
{中略,
 'math': <module 'math' from '/usr/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-cygwin.dll'>}
>>> random = __import__('random')
>>> vars()
{中略,
 'math': <module 'math' from '/usr/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-cygwin.dll'>,
 'random': <module 'random' from '/usr/lib/python3.6/random.py'>}
>>> random.randint(1, 100)
11
>>> from random import randint as ri
>>> vars()
{中略,
 'math': <module 'math' from '/usr/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-cygwin.dll'>,
 'random': <module 'random' from '/usr/lib/python3.6/random.py'>,
 'ri': <bound method Random.randint of <random.Random object at 0x60029f1e8>>}
>>> ri(1, 100)
15

import文は、指定したスクリプトファイルを読み込んでmoduleオブジェクトを作成して変数に代入する処理のシンタックスシュガー(糖衣構文)と言えます。

11
2
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
11
2