Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What really is a keyword in Python?

We can get a list of Python keywords as follows:

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

Cool, but I didn't expect to see False, None, and True there. They are builtin objects.

Why are True, False, and None keywords, but int isn't? What really makes something a keyword in Python?

Edit: I am talking about Python 3

like image 359
multigoodverse Avatar asked Mar 05 '26 07:03

multigoodverse


2 Answers

Keywords are reserved names, so you can't assign to them.

>>> True = 0
  File "<stdin>", line 1
SyntaxError: can't assign to keyword

int is a type; it's perfectly possible to reassign it:

>>> int = str
>>>

(I really wouldn't recommend this, though.)

like image 107
Daniel Roseman Avatar answered Mar 07 '26 20:03

Daniel Roseman


Python isn't like Javascript. In Javascript, you can do things like undefined = "defined" (update: this has been fixed).

Keywords depend on which python you use. Ex: async is a new keyword in 3.7.

Things haven't always been that way though, in Python 2 True = False was valid...

>>> True = False
>>> True
False
>>> True is False
True

So "They are builtin objects.", yes, but new versions of python prevent you from being stupid. This is the only reason why...

New keywords (since Python 2.7) are :

False
None
True
async
await
nonlocal

and of course exec and print aren't keywords anymore.

like image 26
Benoît P Avatar answered Mar 07 '26 20:03

Benoît P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!