組み込み関数dir()

dir()は指定したモジュールで定義されている名前(文字列)のリストを返します。モジュール名を指定しなければしない場合は現在定義されている名前のリストが返ってきます。結果は最初からソートされているのでsorted()とかやる必要はないそうです。


よく利用されるものらしいですが私はあまり利用してません。脱初心者ができていない証かも。それともidle上での話しなのかな?Pythonライブラリリファレンスの「2.1 組み込み関数」に "dir() は第一に対話プロンプトのために提供されている"と書かれてた。開発中に使うものって解釈でよいのかも)


本来の使い方とは違うと思うんだけど、任意の文字列リストが欲しいときなんかに使ったりしてます(サンプルプログラムを書くときの話ね)。

dir()の場合

code
# -*- coding: utf-8 -*-

for m in dir():
    print m
result
__builtins__
__doc__
__file__
__name__

dir(モジュール名)の場合

code
# -*- coding: utf-8 -*-

import sys

#for m in sorted(dir(sys)): ← 無駄
for m in dir(sys):
    print m
result
__displayhook__
__doc__
__egginsert
__excepthook__
__name__
__plen
__stderr__
__stdin__
__stdout__
_current_frames
_getframe
api_version
argv
builtin_module_names
byteorder
call_tracing
callstats
copyright
displayhook
dllhandle
exc_clear
exc_info
exc_type
excepthook
exec_prefix
executable
exit
getcheckinterval
getdefaultencoding
getfilesystemencoding
getrecursionlimit
getrefcount
getwindowsversion
hexversion
maxint
maxunicode
meta_path
modules
path
path_hooks
path_importer_cache
platform
prefix
setcheckinterval
setprofile
setrecursionlimit
settrace
stderr
stdin
stdout
subversion
version
version_info
warnoptions
winver