Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3: What is the difference between keywords and builtins?

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)

like image 684
behzad.nouri Avatar asked Nov 20 '11 20:11

behzad.nouri


1 Answers

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.

like image 128
Raymond Hettinger Avatar answered Sep 28 '22 10:09

Raymond Hettinger