Suggesting methods with similar names

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Mar 30 14:23:42 EST 2005


Raymond Hettinger>When you're done, consider posting the result as an
ASPN cookbook recipe.<

I still cannot write in the cookbook... I think I have problems with
the registration. So you can put it there...
I've found that difflib is good enough for the string matching. This
idea isn't fully mine, it's modified from the Mathematica textual
interface. Here is the code with long lines:

| def __getattr__(self, name):
|     "If a wrong method is called, suggest methods with similar
names."
|     def match(str1, str2):
|         "Return approximate string comparator measure (between 0.0
and 1.0) using difflib."
|         if str1 == str2:
|             return 1.0
|         m1 = SequenceMatcher(None, str1, str2)
|         m2 = SequenceMatcher(None, str2, str1)
|         return (m1.ratio()+m2.ratio()) / 2.0 # average
|
|     toRemove = """__delattr__ __dict__ __getattribute__ __module__
__new__ __reduce__ __copy__
|                __reduce_ex__ __setattr__ __slot__ __weakref__ __str__
__class__ __doc__""".split()
|     methods = set(dir(self.__class__)).difference(toRemove)
|     name = name.lower()
|     matchList = [ (match(name, m.lower()),m) for m in methods ]
|     suggestions = sorted(matchList, reverse=True)[:5] # A heap isn't
necessary here
|     suggestions = ", ".join( pair[1] for pair in suggestions )
|     raise AttributeError, ("method '%s' not found. \nMost similar
named ones: %s" % (name, suggestions))

Note: the general idea of a smart help can be improved a *lot*, this is
the basic version :-]

Bear hugs,
Bearophile




More information about the Python-list mailing list