Suggesting methods with similar names

Benjamin Niemann pink at odahoda.de
Wed Mar 30 17:38:26 CEST 2005


bearophileHUGS at lycos.com wrote:

> I have a class Surface with many methods. Working in the interactive
> window I receive an error like this when I write the wrong method name:
> 
>>>> table.addGlas()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AttributeError: 'Surface' object has no attribute 'addGlas'
> 
> Is it possibile to make the object give a better answer: a short list
> of few method names similar to the one I've misspelled?
> 
> I've found some modules with phonetic algorithms like soundex,
> metaphone, etc, for example here:
> http://sourceforge.net/projects/advas/
> 
> I can produce the list of method names with this:
> toRemove = """__delattr__ __dict__ __getattribute__ __module__ __new__
>            __reduce__ __copy__ __reduce_ex__ __setattr__ __slot__
>            __weakref__ __str__ __class__ __doc__""".split()
> methods = sorted( set(dir(Surface)).difference(toRemove) )
> 
> The problem is calling the phonetic algorithm to show a ranked list of
> the 2-4 method names most similar to the wrong one called. I don't know
> if this problem requires a change in the python shell, or in the
> metaclass of that Surface class, etc.
> And in the end maybe this functionality (inspired by a similar
> Mathematica one) is already inside IPython :-]
You could achieve this by overriding __getattribute__ (untested):

def __getattribute__(self, name):
  try:
    object.__getattribute__(self, name) # or whatever is your superclass
    # or use super(), but I would have to lookup the syntax and
    # breakfast is waiting ;)
  except AttributeError:
    # find similar attributes
    suggestions = ....
    raise AttributeError("'Surface' object has no attribute '%s'. Did you
mean %s?" % (name, suggestions))

I leave it to the experts to wrap this into a generic metaclass, decorator
etc. ;)

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/



More information about the Python-list mailing list