38

I'd like to get a list of all of Pythons keywords as strings. It would also be rather nifty if I could do a similar thing for built in functions.

Something like this :

import syntax
print syntax.keywords
# prints ['print', 'if', 'for', etc...]
wim
  • 338,267
  • 99
  • 616
  • 750
rectangletangle
  • 50,393
  • 94
  • 205
  • 275
  • 5
    Anyway: See the Python language documentation: [Simple statements](http://docs.python.org/reference/simple_stmts.html), [Compund statements](http://docs.python.org/reference/compound_stmts.html) and [Keywords](http://docs.python.org/reference/lexical_analysis.html#keywords). – Sven Marnach Mar 09 '12 at 22:58

6 Answers6

73

They're all listed in the keyword module:

>>> import keyword
>>> keyword.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']

(output as of Python 3.11)

From the keyword.kwlist doc:

Sequence containing all the keywords defined for the interpreter. If any keywords are defined to only be active when particular __future__ statements are in effect, these will be included as well.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
  • Why do __new__, __init__, self, cls, etc. are missing, and how to list them too? – defoe Jun 20 '19 at 20:52
  • @defoe Those aren't keywords: `self` and `cls` are conventional, while `__new__` and `__init__` are magic methods, which have their own question here: [Finding a list of all double-underscore variables?](/q/8920341/4518341) – wjandrea May 23 '23 at 18:16
12

The built-in functions are in a module called __builtins__, so:

dir(__builtins__)
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 3
    If this code is in an imported module, I think it would be `__builtins__.keys()` instead. Or in Python 3, `import builtins` then `dir(builtins)` regardless of module. https://docs.python.org/3/reference/executionmodel.html "By default, when in the `__main__` module, `__builtins__` is the built-in module `builtins`; when in any other module, `__builtins__` is an alias for the dictionary of the `builtins` module itself." – S. Kirby Jun 26 '16 at 07:19
5

The closest approach I can think of is the following:

from keyword import kwlist
print kwlist

The standard keyword module is generated automatically. For other things related to Python parsing from Python, check the language services set of modules.

Regarding listing the builtins I'm not clear if you're asking for items in the __builtin__ module or functions in that package that are implemented directly in the CPython interpreter:

import __builtin__ as B
from inspect import isbuiltin

# You're either asking for this:
print [name for name in dir(B) if isbuiltin(getattr(B, name))]

# Or this:
print dir(B)
C2H5OH
  • 5,452
  • 2
  • 27
  • 39
2

You can import builtins:

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

OR (this does not contain errors and stuff with __ beside them):

>>> help('keywords')

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not                 
class               from                or                  
continue            global              pass                
wjandrea
  • 28,235
  • 9
  • 60
  • 81
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1
>>> help('keywords')

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not                 
class               from                or                  
continue            global              pass
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Sandeep_black
  • 1,352
  • 17
  • 18
-2

The standard keyword module is generated automatically (a Quine) Quine (computing)

>>> import keyword
>>> 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']
>>> len(keyword.kwlist)
33

I categorized the keywords for further reference.

keywords_33 = [
    ('file_2', ['with', 'as']),
    ('module_2', ['from', 'import']),
    ('constant_3', {'bool': ['False', 'True'], 
                    'none': ['None']}),
    ('operator_5', {'logic': ['and', 'not', 'or'],
                    'relation': ['is', 'in']}),
    ('class_1', ['class']),
    ('function_7', ['lambda', 'def', 'pass',
                    'global', 'nonlocal',
                    'return', 'yield']),
    ('loop_4', ['while', 'for', 'continue', 'break']),
    ('condition_3', ['if', 'elif', 'else']),
    ('exception_4', ['try', 'raise', 'except', 'finally']),
    ('debug_2', ['del', 'assert']),
]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 1
    A quine? Quines generate their own source code. I think you're thinking of something else. – wjandrea May 23 '23 at 18:25
  • 1
    I don't think this categorization is really useful. `as` is also used for imports; `with` is used for more than just files (e.g. [Decimal contexts](https://docs.python.org/3/library/decimal.html#context-objects)); `pass` can be used in any block, not just functions; `del` isn't just used for debugging; `try` and `for` can also take `else`... I'm sure there's more. Lastly, why did you put the numbers in the names? – wjandrea May 23 '23 at 18:41