Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Suggesting methods with similar names

Reply
Thread Tools

Suggesting methods with similar names

 
 
bearophileHUGS@lycos.com
Guest
Posts: n/a
 
      03-30-2005
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 :-]

Bye,
Bearophile

 
Reply With Quote
 
 
 
 
Benjamin Niemann
Guest
Posts: n/a
 
      03-30-2005
http://www.velocityreviews.com/forums/(E-Mail Removed) 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/
 
Reply With Quote
 
 
 
 
Terry Reedy
Guest
Posts: n/a
 
      03-30-2005
> You could achieve this by overriding __getattribute__ (untested):

I believe OP would do better to use __getattr__, which is only called when
the attribute is not found by the normal lookup, which is the only time he
needs/wants customized control.

TJR



 
Reply With Quote
 
bearophileHUGS@lycos.com
Guest
Posts: n/a
 
      03-30-2005
Thank you, __getattr__ does what I need
A smart help can be designed easely...

Bear hugs,
Bearophile

 
Reply With Quote
 
Raymond Hettinger
Guest
Posts: n/a
 
      03-30-2005
[Bearophile]
> 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?


[Bearophile]
> Thank you, __getattr__ does what I need
> A smart help can be designed easely...


The idea is a winner. When you're done, consider posting the result as an ASPN
cookbook recipe.


Raymond Hettinger


 
Reply With Quote
 
bearophileHUGS@lycos.com
Guest
Posts: n/a
 
      03-30-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

 
Reply With Quote
 
Diez B. Roggisch
Guest
Posts: n/a
 
      03-30-2005
(E-Mail Removed) 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?


Have you heard of rlcompleter2? It gives you tab-completion on the repl.

While your idea looks nice at first glance, what I don't like about it that
it will make an object return always _something_ - and thus you don't catch
misspellings in non-interactive, or at least not where they actually happen
but when you try to work with the results.

--
Regards,

Diez B. Roggisch
 
Reply With Quote
 
bearophileHUGS@lycos.com
Guest
Posts: n/a
 
      03-30-2005
Diez B. Roggisch>it will make an object return always _something_ - and
thus you don't catch misspellings in non-interactive<

Uhm, I'm sorry, I don't understand you.
If you look at the code I've just posted, you can see that it still
raises AttributeError, the difference is just the error message...

Bearophile

 
Reply With Quote
 
Bengt Richter
Guest
Posts: n/a
 
      03-31-2005
On Wed, 30 Mar 2005 17:55:32 GMT, "Raymond Hettinger" <(E-Mail Removed)> wrote:

>[Bearophile]
>> 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?

>
>[Bearophile]
>> Thank you, __getattr__ does what I need
>> A smart help can be designed easely...

>
>The idea is a winner. When you're done, consider posting the result as an ASPN
>cookbook recipe.
>

Interactively, I often use dir(whatever) to find methods, but I sure wish dir had
some keyword arguments to limit the returned info various ways, e.g., methods
of the immediate class, not the whole mro, and optionally without the __xxx__ methods.
Ditto with help().


BTW, when are we going to be able to write

@classdeco
class Foo(object):
...

so we can implement smart help as a decorator?

I.e., the above decorator syntax would be a non-intrusive way of spelling

class Foo(object):
__metaclass__ = classdeco
...

(haven't thought about cascaded decorators in this context

Regards,
Bengt Richter
 
Reply With Quote
 
Terry Reedy
Guest
Posts: n/a
 
      03-31-2005

"Bengt Richter" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> BTW, when are we going to be able to write
>
> @classdeco
> class Foo(object):


That possibility is currently being discussed for 2.5 on the pydev list.
There are mixed opinions, none yet from Guido that I noticed.

Terry J. Reedy



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Any similar Webcam broadcasting site similar to youtube Chaudhry Nijjhar Computer Support 0 02-19-2008 11:48 PM
Suggesting the use of StandardError as base of error Exceptions. Antoon Pardon Python 3 03-06-2006 04:11 PM
Suggesting a new feature - "Inverse Generators" Jordan Rastrick Python 22 03-27-2005 06:58 AM
Help suggesting new URL richard Computer Support 0 09-29-2003 10:51 AM
Suggesting for overloading the assign operator Rim Python 20 07-08-2003 06:50 PM



Advertisments