0

To get the keywords in python I can use keywords:

import keyword
keyword.keywords
['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']

However, I am looking to find all 'special words' in python for syntax highlighting. For example, the word dir and input (raw_input if python2), set, list, etc. Is there a place that stores all the 'special words' in python -- keywords and elsewhere -- for the purpose of syntax highlighting?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • Syntax highlighting isn't a part of Python. It's entirely up to your syntax highlighter. You can't retrieve this information from Python, because it's not up to Python. – user2357112 Jun 07 '20 at 01:24
  • 1
    You might find `import builtins; dir(builtins)` helpful. See also: https://stackoverflow.com/questions/9642087/is-it-possible-to-get-a-list-of-keywords-in-python – Mark Jun 07 '20 at 01:25
  • 1
    @user2357112supportsMonica: But Python certainly can be used to *identify* these words, which I think is the point of the question. – Scott Hunter Jun 07 '20 at 01:25
  • 1
    @MarkMeyer: Doesn't seem to work in Python2. – Scott Hunter Jun 07 '20 at 01:27
  • I think you'll find it's `keyword.kwlist`, in Python3 anyway, which is the only Python that matters now - you should *not* be using Python2. – paxdiablo Jun 07 '20 at 01:27
  • @ScottHunter: You can use Python to identify "everything in the builtin namespace", but there's no guarantee that that's the exact list of names your syntax highlighter will treat specially. It's probably not, in most cases. – user2357112 Jun 07 '20 at 01:29
  • 1
    @user2357112supportsMonica I got the impression the op was trying to *create* a highlighting function. – Mark Jun 07 '20 at 01:29

1 Answers1

2

These are called built-in functions. From this answer you can use an approach like this. You also have types (int and list for example). Add those to your keywords and you should have fairly complete coverage.

import builtins
import inspect

builtin_functions = [name for name, function in sorted(vars(builtins).items()) if inspect.isbuiltin(function) or inspect.isfunction(function)]
types = [name for name, function in sorted(vars(builtins).items()) if type(function) == type]

Or for python 2

import __builtin__
import inspect

builtin_functions = [name for name, function in sorted(vars(__builtin__).items()) if inspect.isbuiltin(function) or inspect.isfunction(function)]
types = [name for name, function in sorted(vars(__builtin__).items()) if type(function) == type]
Dominic D
  • 1,778
  • 2
  • 5
  • 12