simple tab completion

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

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

#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
            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")

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

Jeff Schroeder —

2009-07-12 07:38:00

Check out this extended version of your python tab completion trick full on history support: