Python / 内省的(introspective)とはどういうことか

前の投稿からの続きです。

内省的とは、「内部を省みることに長けている」ということです。

ところで。 プログラミング言語を選択する場合、何を重視すべきかいつも悩みます。 結論として、『言語を選択することは環境を選択することだ』というのに辿り着きました。

言語が優れていても、エディタやIDEが整っていなければ、プログラミングを継続できません。 良い食材があっても、コンロの火力が足りなくては美味しい料理にならないようなものです。

Pythonは内部を見通すことのできる、使いやすいシンプルな環境が揃っています。

ここではひと通り使ってみることで、それを示してみようと思います。 コンソールから起動すると対話環境に入れます。


  $ python

  Python 3.3.5 (default, Aug 22 2014, 05:29:41)
  [GCC 4.7.3] on linux
  Type "help", "copyright", "credits" or "license" for more information.
  >>>

"dir()"を打つとトップレベルの変数が見えます。


  >>> dir()
  ['__builtins__', '__doc__', '__loader__', '__name__', '__package__']

"'__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', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroPisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'pmod', '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']

helpでドキュメントが見れます。


  >>> help(max)

Help on built-in function max in module builtins:

max(...)
    max(iterable[, key=func]) -> value
    max(a, b, c, ...[, key=func]) -> value
    
    With a single iterable argument, return its largest item.
    With two or more arguments, return the largest argument.

実に便利です。


>>> max(1,2,3,4,5)
5

エディタでPythonコードを書いて、hoge.pyとして保存します。その後、同じディレクトリで対話環境を起動します。


# hoge.py
def hoge():
    print('hoge')

hogeをimportすると……


>>> import hoge
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', 'hoge', 'sy
s']                                                                            

トップレベルにhogeモジュールが読み込まれます。


>>> hoge.hoge()
hoge

hoge.hoge()を呼び出すことが出来ました。


# 'hoge.py'
def hoge():
    print('fuga')

書き換えて……


>>> import imp
>>> imp.reload(hoge)
<module 'hoge' from='hoge.py'>
>>> hoge.hoge()
fuga

imp.reloadで読み込み直すと、変更が反映されます。

このサイクルを繰り返せばよいわけです。 さらに、Djangoやwsgi等のフレームワークを使用した場合は大概リロードすら自動にやってくれます。 また、ユニットテストが標準にあるように、Pythonのライブラリは膨大です。 必要な機能は大概手に入ります。

斯様に、すっきりと管理されていて、使いやすさを至上の命題としている様が見受けられるのが、Pythonの魅力です。 そして、これが前の投稿で残しておいたPythonを好む理由の一つです。

  • ドキュメントが整っていて内省的(introspective)であったこと

──続きます。

参考文献

関連して、IBMが有用な文章を公開してくれていますので紹介します。

IBM Pythonイントロスペクション入門

目録

  1. Python / 不便が便利
  2. Python / 内省的(introspective)とはどういうことか
  3. Python / 第一級関数と無名関数
  4. Python / デコレータは愉快
  5. Python / デコレータと引数
  6. Python / デコレータのカスタム
  7. Python / IndentデコレータとChoiceデコレータ

0 件のコメント:

コメントを投稿