Heisenberg strikes again!

Michael Pyle mpyle at legato.com
Wed Sep 10 17:36:44 EDT 2003


A couple of things, first I think you want comp() to return matches[state]
not commands[state]. Second, inside of comp() you need to tell python that
you want the global variable matches and not the local one that gets created
when state == 0.

This version seems to work properly:

#!/usr/bin/python

import readline
import sys

commands = ["one", "two", "three", "four"]
matches = []

def comp(text, state):
    global matches
    if state == 0:
        matches = []
        n = len(text)
        for cmd in commands:
            if cmd[:n] == text:
                matches.append(cmd)
    throwaway = matches[0]   # <--- Comment out this line
    return matches[state]

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

while 1:
    try:
        line = raw_input("> ")
    except EOFError:
        print "\n",
        sys.exit()
    print ": %s" % line


--Michael Pyle
--Legato Systems, Inc.

-----Original Message-----
From: google at elesi.org [mailto:google at elesi.org] 
Sent: Wednesday, September 10, 2003 1:54 PM
To: python-list at python.org
Subject: Heisenberg strikes again!

Alright, I'm fairly new to Python, and this one has got me stumped. 
I've just started to write a cli program that'll use readline, and
I've attached the relevant bits.

Here's the mystery:  If I so much as /look/ at the list 'matches',
readline stops working.  Run the program, hit tab at the prompt,
you'll get 'one', which is incorrect, as there are in fact four
possible completions.  Now comment out the line that I've marked
(which, incidentally, does nothing).  /Now/ it works.

Is there some very strange side effect to accessing a list element
that I'm unaware of?  I've tried it in two different versions of
Python.

Any elightenment would be appreciated...

Heath

ps In terms of being useful, this program doesn't make any sense.  I'm
not trying to get it to work, I'm looking to understand why the
commented line affects the rest of the code.


#!/usr/bin/python

import readline
import sys

commands = ["one", "two", "three", "four"]
matches = []

def comp(text, state):
    if state == 0:
        matches = []
        n = len(text)
        for cmd in commands:
            if cmd[:n] == text:
                matches.append(cmd)
    throwaway = matches[0]   # <--- Comment out this line
    return commands[state]

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

while 1:
    try:
        line = raw_input("> ")
    except EOFError:
        print "\n",
        sys.exit()
    print ": %s" % line
-- 
http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20030910/19e3dbf6/attachment.html>


More information about the Python-list mailing list