โมดูล keyword ในไลบรารีมาตรฐานของ Python ช่วยตรวจสอบว่าสตริงใดเป็น keyword ของภาษา Python
ฟังก์ชันหลัก
- keyword.iskeyword(s): คืนค่า True ถ้า s เป็น keyword ของ Python
- keyword.kwlist: คืนค่า sequence ของ keywords ทั้งหมดที่ interpreter กำหนด (รวม keywords ที่จะเพิ่มในอนาคต)
ตัวอย่างการใช้งาน
>>> import keyword
>>> kwlist = keyword.kwlist
>>> kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']
>>> kw = input('enter a keyword..')
enter a keyword..catch
>>> kw in kwlist
False
>>> kw = input('enter a keyword..')
enter a keyword..import
>>> kw in kwlist
True
รายการ Keywords ทั้งหมด (Python 3.7+)
| Keyword | คำอธิบาย |
|---|---|
| False, None, True | ค่าคงที่ในตัว (singletons) |
| and, or, not | Boolean operators |
| as | Alias ใน import/exception handling |
| assert | Debugging assertion |
| async, await | Asynchronous programming |
| break, continue | ควบคุม Loop |
| class | สร้าง Class |
| def | สร้าง Function |
| del | ลบ Object/Attribute |
| elif, else | Conditional branching |
| except, finally, try | Exception handling |
| for, while | Loop statements |
| from, import | Module import |
| global, nonlocal | Variable scope |
| in | Membership test / Loop iteration |
| is | Identity test |
| lambda | Anonymous function |
| pass | Null statement |
| raise | Raise exception |
| return | Return from function |
| with | Context manager |
| yield | Generator function |
ข้อควรทราบ
- Keywords เป็นคำสงวน ไม่สามารถใช้เป็นชื่อตัวแปร ฟังก์ชัน คลาส โมดูล ได้
- รายการอาจเพิ่มขึ้นในเวอร์ชันใหม่ (เช่น
async,awaitเพิ่มใน Python 3.5) - ใช้
keyword.iskeyword()ตรวจสอบก่อนตั้งชื่อได้ - Soft keywords (Python 3.10+):
match,case,_(ใช้ใน pattern matching)