34

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?

Mike Vella
  • 9,582
  • 13
  • 55
  • 84
  • 1
    related: [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 Answers2

79

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
  • 59,056
  • 16
  • 119
  • 195
15

You can check a specific keyword as well

import keyword
keyword.iskeyword("print") # TRUE
Thai Tran
  • 9,607
  • 7
  • 41
  • 62