Python/モジュールのインポート

出典: フリー教科書『ウィキブックス(Wikibooks)』



モジュール化(modularization / modularize)は、全体をいくつかの構成単位に分割し、問題の規模と質を低減する分割統治法(divide-and-conquer method)の一つです。 Pythonでは、パッケージ(package)とモジュール(module)がモジュール化の実現に用いられます。 このうち、パッケージはモジュールの構造的な整理手段と考えられ、まずモジュールの用途・用法について解説し、モジュールをユーザーが定義する具体的な例も示します。

モジュールmath[編集]

平方根などの数学に関する関数を使用したい場合は、モジュールmathをインポートします。

モジュールmathの関数「sqrt()」を使い平方根を求める
import math

print(math.sqrt(2))

help(math.sqrt)
実行結果
1.4142135623730951
Help on built-in function sqrt in module math:

sqrt(x, /)
    Return the square root of x.
構文
import モジュール名

また、インポートされた関数をつかうときは、どのモジュールに由来する関数かを、pythonが判断できるようにするために、「math.sqrt()」のように、関数の前にモジュール名を書きます。 「.」はドット記号です。つまり、「モジュール名.関数名」のような書式になります。

モジュールmathでは、三角関数や指数関数なども、使えます。三角関数の単位は、ラジアンです。

※ ラジアンは弧度法の角度の単位で記号は rad です。とはなにか、高校で習います。度数法で円周は360°ですが、弧度法では2π rad です。
モジュールmathの関数「sin()」を使い正弦を求める
import math

print(math.sin(math.pi/4))
実行結果
0.7071067811865475

モジュールmathの属性一覧[編集]

モジュールmathの属性一覧
import math

mod = math
print(f"""\
{{| class="wikitable"
|+ {type(mod).__name__} {mod.__name__}の属性一覧
|-
!属性!!値!!__doc__\
""")

for k,v in vars(mod).items():
    print(f"""\
|-
! {k}
| {repr(v)}
| {getattr(v, "__doc__").splitlines()[0]}\
""")
print("|}}")
module mathの属性一覧
属性 __doc__
__name__ 'math' str(object=) -> str
__doc__ 'This module provides access to the mathematical functions\ndefined by the C standard.' str(object=) -> str
__package__ str(object=) -> str
__loader__ <class '_frozen_importlib.BuiltinImporter'> Meta path import for built-in modules.
__spec__ ModuleSpec(name='math', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in') The specification for a module, used for loading.
acos <built-in function acos> Return the arc cosine (measured in radians) of x.
acosh <built-in function acosh> Return the inverse hyperbolic cosine of x.
asin <built-in function asin> Return the arc sine (measured in radians) of x.
asinh <built-in function asinh> Return the inverse hyperbolic sine of x.
atan <built-in function atan> Return the arc tangent (measured in radians) of x.
atan2 <built-in function atan2> Return the arc tangent (measured in radians) of y/x.
atanh <built-in function atanh> Return the inverse hyperbolic tangent of x.
ceil <built-in function ceil> Return the ceiling of x as an Integral.
copysign <built-in function copysign> Return a float with the magnitude (absolute value) of x but the sign of y.
cos <built-in function cos> Return the cosine of x (measured in radians).
cosh <built-in function cosh> Return the hyperbolic cosine of x.
degrees <built-in function degrees> Convert angle x from radians to degrees.
dist <built-in function dist> Return the Euclidean distance between two points p and q.
erf <built-in function erf> Error function at x.
erfc <built-in function erfc> Complementary error function at x.
exp <built-in function exp> Return e raised to the power of x.
expm1 <built-in function expm1> Return exp(x)-1.
fabs <built-in function fabs> Return the absolute value of the float x.
factorial <built-in function factorial> Find x!.
floor <built-in function floor> Return the floor of x as an Integral.
fmod <built-in function fmod> Return fmod(x, y), according to platform C.
frexp <built-in function frexp> Return the mantissa and exponent of x, as pair (m, e).
fsum <built-in function fsum> Return an accurate floating point sum of values in the iterable seq.
gamma <built-in function gamma> Gamma function at x.
gcd <built-in function gcd> greatest common divisor of x and y
hypot <built-in function hypot> hypot(*coordinates) -> value
isclose <built-in function isclose> Determine whether two floating point numbers are close in value.
isfinite <built-in function isfinite> Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf <built-in function isinf> Return True if x is a positive or negative infinity, and False otherwise.
isnan <built-in function isnan> Return True if x is a NaN (not a number), and False otherwise.
isqrt <built-in function isqrt> Return the integer part of the square root of the input.
ldexp <built-in function ldexp> Return x * (2**i).
lgamma <built-in function lgamma> Natural logarithm of absolute value of Gamma function at x.
log <built-in function log> log(x, [base=math.e])
log1p <built-in function log1p> Return the natural logarithm of 1+x (base e).
log10 <built-in function log10> Return the base 10 logarithm of x.
log2 <built-in function log2> Return the base 2 logarithm of x.
modf <built-in function modf> Return the fractional and integer parts of x.
pow <built-in function pow> Return x**y (x to the power of y).
radians <built-in function radians> Convert angle x from degrees to radians.
remainder <built-in function remainder> Difference between x and the closest integer multiple of y.
sin <built-in function sin> Return the sine of x (measured in radians).
sinh <built-in function sinh> Return the hyperbolic sine of x.
sqrt <built-in function sqrt> Return the square root of x.
tan <built-in function tan> Return the tangent of x (measured in radians).
tanh <built-in function tanh> Return the hyperbolic tangent of x.
trunc <built-in function trunc> Truncates the Real x to the nearest Integral toward 0.
prod <built-in function prod> Calculate the product of all the elements in the input iterable.
perm <built-in function perm> Number of ways to choose k items from n items without repetition and with order.
comb <built-in function comb> Number of ways to choose k items from n items without repetition and without order.
pi 3.141592653589793 Convert a string or number to a floating point number, if possible.
e 2.718281828459045 Convert a string or number to a floating point number, if possible.
tau 6.283185307179586 Convert a string or number to a floating point number, if possible.
inf inf Convert a string or number to a floating point number, if possible.
nan nan Convert a string or number to a floating point number, if possible.

モジュールrandom[編集]

サイコロの目のような、乱数をつかうには、モジュールrandomをインポートします。

モジュールmathの関数「sqrt()」を使い乱数を得る
import random

for _ in range(32):
    print(random.randint(1, 6), end=" ")
実行結果
1 2 3 1 3 6 3 3 5 6 4 5 2 1 5 2 2 2 4 4 5 1 2 6 5 5 1 2 1 5 3 5
randint(a, b)により、a以上でb以下の整数を、不規則に表示することができます。

ローカル名前空間へのインポート[編集]

たとえばモジュールmathから、sqrtだけをローカル名前空間へインポートしたい場合、コードが次のようになります。

mathで定義されているsqrtを全てローカル名前空間にインポート
from math import sqrt

a = sqrt(2)
print(a)
実行結果
1.4142135623730951
構文
from モジュール名 import インポートする識別子
の書式により、特定の関数だけを選んでインポートできます。
ローカル名前空間にインポートした識別子は、「math.」をつけず、そのまま「sqrt(2)」のように呼び出せます。
mathで定義されている識別子を全てローカル名前空間にインポート
from math import *

print(f"{sqrt(2)=}")
print(f"{pi =}")
実行結果
sqrt(2)=1.4142135623730951
pi =3.141592653589793
* を指定しても、アンダースコア _ で始まる識別子はインポートされません。

ユーザー定義モジュール[編集]

ここまでは、標準ライブラリーのモジュールを紹介してきましたが、モジュールはユーザー自身で定義することもできます。

モジュール定義[編集]

ここでは、与えられた数が素数か否かを判定するモジュール isprime を作ってみましょう。

isprime.py
"""
isprime:
  Determine if a given number is prime
Usage:
  import isprime
  
  isprime.isprime(42)
  
    OR

  from isprime import isprime
  
  isprime(4423)
"""


_primes = set()
_noprimes = set()

def isprime(x :int) -> bool :
    '''
    >>> isprime(2)
    True
    >>> isprime(10)
    False
    '''
    if x in _primes:
        return True
    if x in _noprimes:
        return False
    if x <= 1:
        return False
    i = 2
    while i*i <= x:
        if x%i == 0:
            _noprimes.add(x)
            return False
        i += 1
    _primes.add(x)
    return True

if __name__ == '__main__':
    assert not isprime(-1)
    assert not isprime(0)
    assert not isprime(1)
    assert isprime(2)
    assert isprime(3)
    assert not isprime(4)
    help(isprime)
アンダースコア _ で始まる識別子は、from MODULE import * でローカル名前空間に読み込まれません。
過去に素数判定を行った履歴を残し、履歴に残った判定結果を再利用するためにだけ使うので、アンダースコア _ を前置してモジュール内だけで使うことを表しました[1]
isprimeだけがモジュール外から可視化された識別子となります。
if __name__ == '__main__':以下は、このファイルがモジュールではなく、メインスクリプトとして実行されたときに評価され、回帰テストなどを書くことが一般的です。

モジュールのインポートと識別子を使った参照[編集]

Main.py
import isprime

hash = {}
for x in range(100):
    hash[x] = isprime.isprime(x)
print(hash)

help(isprime)
実行結果
{0: False, 1: False, 2: True, 3: True, 4: False, 5: True, 6: False, 7: True, 8: False, 9: False, 10: False, 11: True, 12: False, 13: True, 14: False, 15: False, 16: False, 17: True, 18: False, 19: True, 20: False, 21: False, 22: False, 23: True, 24: False, 25: False, 26: False, 27: False, 28: False, 29: True, 30: False, 31: True, 32: False, 33: False, 34: False, 35: False, 36: False, 37: True, 38: False, 39: False, 40: False, 41: True, 42: False, 43: True, 44: False, 45: False, 46: False, 47: True, 48: False, 49: False, 50: False, 51: False, 52: False, 53: True, 54: False, 55: False, 56: False, 57: False, 58: False, 59: True, 60: False, 61: True, 62: False, 63: False, 64: False, 65: False, 66: False, 67: True, 68: False, 69: False, 70: False, 71: True, 72: False, 73: True, 74: False, 75: False, 76: False, 77: False, 78: False, 79: True, 80: False, 81: False, 82: False, 83: True, 84: False, 85: False, 86: False, 87: False, 88: False, 89: True, 90: False, 91: False, 92: False, 93: False, 94: False, 95: False, 96: False, 97: True, 98: False, 99: False}
Help on module isprime:

NAME
    isprime

DESCRIPTION
    isprime:
      Determine if a given number is prime
    Usage:
      import isprime
      
      isprime.isprime(42)
      
        OR
    
      from isprime import isprime
      
      isprime(4423)

FUNCTIONS
    isprime(x: int) -> bool
        >>> isprime(2)
        True
        >>> isprime(10)
        False

FILE
    /workspace/isprime.py
help()関数にモジュールを渡すと __docstring__ がレンダリングされます。


脚註[編集]

  1. ^ from isprime import _primes とすれば _primes としてローカル空間に現れるので、隠蔽という意味では完全ではなく、「将来の実装では参照できることを保証しません」程度の意味です(意訳:使うな!)。