Python のモジュールいろいろ

引続き勉強中

import構文

Pythonチュートリアル6章に記載の以下のモジュールを定義する(fibo.py)

def fib(n):
    a, b = 0, 1
    while b < n:
        print(b, end=" ")
        a, b = b, a + b
    print()


def fib2(n):
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a + b
    return result

if __name__ == "__main__":
    import sys
    print(argv)
    fib(int(sys.argv[1]))

インポート構文は以下の2パターン

  • モジュール名を取り込む
>>> import fibo
>>> fibo.fib(10)
1 1 2 3 5 8 
>>> fibo.fib2(10)
[1, 1, 2, 3, 5, 8]
>>> fib(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fib' is not defined
  • モジュール名はローカルに取り入れず、モジュール内で定義されている名前のみ取り込む(非推奨だが * も使える)
>>> from fibo import fib, fib2 
>>> fib(5)
1 1 2 3 
>>> fib2(5)
[1, 1, 2, 3]
>>> fibo.fib(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fibo' is not defined

モジュールが定義している名前の確認方法

  • 組み込みモジュール dir() を使う
  • モジュールに定義されている名前と、関数に定義されている名前を比べてみた
    • これ意味わかるようになるまで大変だな…。
    • 関数内で定義されている名前に result. a. bが見当たらないのはなぜ。
>>> import fibo
>>> dir(fibo)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'argv', 'fib', 'fib2']
>>> from fibo import fib
>>> dir(fib)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
  • dir(), 面白い
  • 何かしらの中身が知りたければ片っ端からdir()してみる?
>>> import builtins
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'builtins']
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

pycache の正体

  • コンパイル済みのモジュール(.pyc)をキャッシュとして格納
  • モジュールのimport時に生成される
  • 読み込みが早くなる
  • import fibo したときと from fibo import fib したときで生成されるキャッシュのmd5ハッシュをみてみたけど一緒だった。
    • 特定の関数だけimportしても結局モジュールまるごとコンパイルしているのかな。