Python入門(8) Pythonの予約語
いまさらであるが、プログラム言語ではいくつかの文字列は他の目的のために変数名などに使うことを禁止している。 それらの語を予約語( reserved word)という。
Pythonでは予約語はversionによって多少違っている。 次のはPython.27の予約語である。 次は
and | as | assert | break | class | continue |
def | del | elif | else | except | exec |
finally | for | from | global | if | import |
in | is | lambda | not | or | pass |
raise | return | try | while | with | |
yield |
予約語の取得
今使っているPythonでの予約語は次のようにして知ることができる。 keywordモジュールをインポートすると、keyword.kwlistにリストとして格納されている(一行が折り返されて表示されないので、横にスクロールしてして欲しい)。
>>> import keyword >>> keyword.kwlist >>> ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] >>> len(keyword.kwlist) 31
自分で定義できる変数名や関数名には、予約語はもちろん使えないが、Pythonの標準的クラスや組み込み関数とも重ならないようにする配慮も必要だ。
for int in keyword.kwlist: print int
上のように書くことはできるが、int は整数型 int としての意味があるので、コードの可読性を低下させてしまう。
>>> i = 3 >>> type(i) int