I'm writing a program which does some code generation to python and need to treat a string differently if it is a python keyword. help(keywords)
prints the python keywords and some extra stuff, but I wonder if there's a pythonic way to get an actual iterable object with these strings in it?
Asked
Active
Viewed 2.5k times
35

Mike Vella
- 10,187
- 14
- 59
- 86
-
1related: [Is it possible to get a list of all Python statements in Python?](http://stackoverflow.com/questions/9642087/is-it-possible-to-get-a-list-of-all-python-statements-in-python) – jfs Jan 30 '13 at 03:07
2 Answers
80
You are better of using the keyword module
>>> 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']

Abhijit
- 62,056
- 18
- 131
- 204
16
You can check a specific keyword as well
import keyword
keyword.iskeyword("print") # TRUE

Thai Tran
- 9,815
- 7
- 43
- 64