How to get the special method names by reflection?
Jim Jinkins
jjinkins at comports.com
Mon May 12 18:07:33 EDT 2003
Each new version of Python is likely to change the lists of keywords,
builtin names, special method names, etc. Working through these lists
to update the syntax coloring file definitions for my favorite editors
has been time-consuming and error-prone.
I wrote the program below to make it easier for me and for anyone who
has a different editor. It automatically gets keywords, builtin names,
and object methods.
But the only way I have figured out to get the special method names is
to cut and paste from the online Python Reference, then extract the
names with the program. __add__, __hash__, and __getitem__ are examples
of special names.
Is a way to get the special method names by reflection? Is there
another group of words that should be highlighted?
Thanks,
Jim Jinkins <Jim -dot_ Jinkins _at- ComPorts :dot: com>
# MakeSyntaxList.py
"""Make lists of Python symbols to cut and paste into a syntax coloring file
In this version the special method names in file SpecialMethods.txt are
obtained by extracting all sections from the Python Reference
Manual, Section 3.3 Special Names.
Redirect this program's stdout to a text file. Cut and paste to build a
syntax coloring file for your prefered programmer's editor.
"""
import keyword
import types
import re
import sys
def printList(lst, title):
print "\n\n\n;;;;;;;; %s ;;;;;;;;" % title
for le in lst:
print le
if __name__ == "__main__":
all_keywords = keyword.kwlist
all_keywords.sort()
all_builtins = dir(__builtins__)
all_builtins.sort()
# Split all_builtins
builtinExceptions = []
builtinNonExceptions = []
for s in all_builtins:
if s in ["license", "copyright", "credits", "help"]:
builtinNonExceptions.append(s)
else:
try:
obj = eval("%s()" % s)
if isinstance(obj, Exception):
builtinExceptions.append(s)
else:
builtinNonExceptions.append(s)
except Exception, e:
builtinNonExceptions.append(s)
all_types = dir(types)
all_types.sort()
object_methods = dir(object)
object_methods.sort()
try:
f = open("SpecialMethods.txt", "r")
except IOError, e:
print "%s" % e
print "Create SpecialMethods.txt by extracting all text from the "
print "Python Reference Manual, Section 3.3 Special Names."
sys.exit(1)
lines = f.readlines()
f.close()
pat = re.compile("^.*(__([a-zA-Z0-9]+(_[a-zA-Z0-9]+)*)__).*$")
sms = []
for ln in lines:
m = pat.match(ln)
if m:
sms.append(m.group(1))
sms.sort()
# Remove duplicate names
special_methods = [sms[0]] + [sms[i] for i in range(1, len(sms))
if sms[i] != sms[i - 1]]
printList(all_keywords, "Python keywords")
# printList(all_builtins, "All builtin names")
printList(builtinNonExceptions, "Builtin names not including
exceptions")
printList(builtinExceptions, "Builtin exception classes")
printList(object_methods, "Object methods")
printList(special_methods, "Special methods")
printList(all_types, "Type names")
More information about the Python-list
mailing list