16
votes

In python 3,

>>> import keyword
>>> keyword.kwlist

and

>>> import builtins
>>> dir(builtins)

are two different lists, yet they have some common values, specifically

>>> set(dir(builtins)) & set(keyword.kwlist)
{'False', 'True', 'None'}

What is the difference of keywords and builtins in python? and when are 'False', 'None', 'True' keywords and when are they builtins? (if that makes any difference)

1

1 Answers

23
votes

Keywords are core language constructs handled by the parser. These words are reserved and cannot be used as identifiers: http://docs.python.org/reference/lexical_analysis.html#keywords

Builtins are a list of commonly used, preloaded functions, constants, types, and exceptions: http://docs.python.org/library/functions.html

In Python 3, the overlapping words, False, None, and True are builtin constants that are protected from assignment by the parser. This prevents accidental overwriting with something like True=10. As a keyword, this assignment can be blocked:

>>> True = 10
SyntaxError: assignment to keyword

The remaining builtins are not protected and could be reassigned with something like __builtins__.list = mylist.