Retrieving Python Keywords

Chris Angelico rosuav at gmail.com
Sun Apr 10 03:57:39 CEST 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>
    eval("foo")
  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>
    eval("lambda")
  File "<string>", line 1
    lambda
         ^
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