Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get a list of keywords in Python?

I'd like to get a list of all of Pythons keywords as strings. It would also be rather nifty if I could do a similar thing for built in functions.

Something like this :

import syntax print syntax.keywords # prints ['print', 'if', 'for', etc...] 
like image 728
rectangletangle Avatar asked Mar 09 '12 22:03

rectangletangle


People also ask

How do I get a list of keywords?

To print the list of all keywords, we use "keyword. kwlist", which can be used after importing the "keyword" module, it returns a list of the keyword available in the current Python version. In the below code, we are implementing a Python program to print the list of all keywords.

What are the 33 keywords in Python?

In Python, there are approximately around thirty-three (33) keywords, and a few of the keywords generally used in the program coding are break, continue, true, false, and, or, not, for, while, def, class, if, else, elif, import, from, except, exec, print, return, yield, lambda, global, etc.

Is list a key word in Python?

list is not a keyword but a built-in type, as are str , set , dict , unicode , int , float , etc. There is no point in reserving each and every possible built-in type; python is a dynamic language and if you want to replace the built-in types with a local name that shadows it, you should be able to.


1 Answers

You asked about statements, while showing keywords in your output example.

If you're looking for keywords, they're all listed in the keyword module:

>>> import keyword >>> keyword.kwlist ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',  'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',  'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',  'while', 'with', 'yield'] 

From the keyword.kwlist doc:

Sequence containing all the keywords defined for the interpreter. If any keywords are defined to only be active when particular __future__ statements are in effect, these will be included as well.

like image 178
Rik Poggi Avatar answered Sep 21 '22 22:09

Rik Poggi