Retrieving Python Keywords

John Connor john.theman.connor at gmail.com
Sat Apr 9 22:09:42 EDT 2011


Actually this is all it takes:
import keywords
print keywords.kwlist

--jac

On Sat, Apr 9, 2011 at 8:57 PM, Chris Angelico <rosuav at gmail.com> wrote:
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list