python的keyword模块记录了python所有的关键字,它的作用是避免因为变量命名冲突而造成异常。他所有的关键字都已列表的形式存放在kwlist属性中。
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
这个模块还提供了iskeyword方法来判断变量名是否是关键字。
import keyword
print(keyword.iskeyword('break'))
print(keyword.iskeyword('break_'))
True
False