153

Is the list of Python reserved words and builtins available in a library? I want to do something like:

 from x.y import reserved_words_and_builtins

 if x in reserved_words_and_builtins:
     x += '_'
Neil G
  • 32,138
  • 39
  • 156
  • 257
  • possible duplicate of [List of python keywords](http://stackoverflow.com/questions/14595922/list-of-python-keywords) – Abhijit Apr 05 '14 at 15:04
  • 3
    @Abhijit: The main difference is that I asked for all reserved words including built-ins. – Neil G Apr 06 '14 at 19:30
  • edit: apparently many people use "reserved word" to be synonymous with keyword. I've edited the question accordingly. – Neil G Mar 13 '15 at 20:21
  • @NeilG I'm pretty sure they are synonyms in Python. Builtins are definitely not reserved words, since they can be reassigned, e.g. `print = None`. – wjandrea Jul 01 '20 at 17:47

1 Answers1

224

To verify that a string is a keyword you can use keyword.iskeyword; to get the list of reserved keywords you can use keyword.kwlist:

>>> import keyword
>>> keyword.iskeyword('break')
True
>>> 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']

If you want to include built-in names as well (Python 3), then check the builtins module:

>>> 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', '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', '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']

For Python 2 you'll need to use the __builtin__ module

>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 12
    Note that in python2.6<=x.y<3.0 `None` is *not* formally a keyword (according to `kwlist` and `iskeyword`) but it *is* actually a keyword (because `None = 1` fails with a `SyntaxError`), although it is listed as built-in together with `True` and `False`. – Bakuriu Apr 05 '14 at 11:26
  • 5
    Just out of curiosity, what is the philosophical justification for having a distinction between keywords and builtins? Shouldn't they all just be reserved? – notconfusing Oct 20 '14 at 22:16
  • 16
    @notconfusing: keywords are part of the language's grammar. Builtins act as if you had done `from builtins import *`; they can be overridden. – Neil G Nov 11 '14 at 18:20
  • 5
    @notconfusing: In particular, minimizing keywords means that common words aren't needlessly unavailable in *safe* scenarios. Sure, assigning `set = 1` is a terrible idea, but a class with a method or attribute named `set` (so it's always referenced with `instance.set`, not as plain `set`) isn't necessarily awful. There are perfectly legitimate cases for naming a method `set`; if `set` was a keyword, you couldn't do that. – ShadowRanger Sep 25 '18 at 19:07
  • Any idea why the [special method names](https://docs.python.org/3/reference/datamodel.html#special-method-names) are not included? – wwii Jun 21 '19 at 13:50
  • I updated the answer with the latest python 3.* reserved keywords. – Kushan Gunasekera Jun 24 '19 at 08:16
  • 2
    @wwii The special method names aren't globally defined like builtins, or part of the syntax like keywords. `__len__` on its own means nothing. You have to say `str.__len__` or `list.__len__`. So there's no worries about your variable names colliding with them. – Nick S Aug 12 '19 at 23:52
  • Note that, at least as of Python 3.9, `None` is now included in the list of keywords; `keyword.iskeyword('None')` returns `True`. – hlongmore Feb 21 '23 at 03:48