Retrieving Python Keywords

Chris Angelico rosuav at
Sat Apr 9 21:57:39 EDT 2011

On Sun, Apr 10, 2011 at 11:28 AM, candide <candide at free.invalid> wrote:
> Python is very good at introspection, so I was wondering if Python (2.7)
> provides any feature to retrieve the list of its keywords (and, as, assert,
> break, ...).

I don't know about any other way, but here's a really REALLY stupid
method. For every possible alphabetic string, attempt to eval() it; if
you get NameError or no error at all, then it's not a keyword.
SyntaxError means it's a keyword.

>>> eval("foo")

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
>>> eval("lambda")

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
  File "<string>", line 1
SyntaxError: unexpected EOF while parsing
>>> eval("eval")
<built-in function eval>

Yes, it's stupid. But I'm feeling rather mischievous today. :)

Chris Angelico

More information about the Python-list mailing list