simple tab completion

Tuesday 14 November 2006, 01:00:00 | python

Use custom tab-completion in your console programs, like this:

#from http://effbot.org/librarybook/readline.htm
#You do it like this,

class Completer:
    def __init__(self, words):
        self.words = words
        self.prefix = None
    def complete(self, prefix, index):
        if prefix != self.prefix:
            self.matching_words = [w for w in self.words if w.startswith(prefix)]
            self.prefix = prefix
        try:
            return self.matching_words[index]
        except IndexError:
            return None

import readline

# a set of more or less interesting words
validanswers = [ 'yes', 'no', 'maybe', 'tuesday', 'never' ]

completer = Completer(validanswers)

readline.parse_and_bind("tab: complete")
readline.set_completer(completer.complete)

# try it out!
while True:
    answer = raw_input("Answer the Question: ")
    if answer not in validanswers:
       print "Wrong!"
    else:
       print "Your answer is",answer
People have replied:

Jeff Schroeder — http://www.digitalprognosis.com

2009-07-12 07:38:00

Check out this extended version of your python tab completion trick full on history support: http://www.digitalprognosis.com/opensource/scripts/pythonrc