[Python-ideas] Default value for input

Steven D'Aprano steve at pearwood.info
Tue Apr 1 13:58:43 CEST 2014


(I'm talking about Python 3 input, previously known as raw_input.)

I often have the need to include a default or initial value when 
asking the user for input. In other words, I'd like to call this:

input("What is the fish of the day? ", "trout a la creme")


and have the prompt be "What is the fish of the day? " and the initial 
value in the edit buffer be "trout a la creme", fully editable with 
whatever line editing tools are available on the user's system. There 
are work-arounds for this lack, but they don't make a nice clean UI.

Under Linux, with readline, I can implement this relatively simply:


_input = input
def input(prompt, initial=''):
    readline.set_startup_hook(lambda: readline.insert_text(initial))
    try:
        return _input(prompt)
    finally:
        readline.set_startup_hook(None)


Aside: I'm a bit concerned about unconditionally setting the startup 
hook to None, rather than restoring whatever it was before I messed with 
it. But I see no way to save the startup hood from Python code.

However this doesn't work under Windows, or any other system where 
readline is not available.

Does anyone else think this would be a useful feature? I see a few 
questions about this in various places, such as StackOverflow:

http://stackoverflow.com/questions/5403138/how-to-set-a-default-string-for-raw-input

but I don't see that it has ever been requested on the bug tracker.

Is it practical to include an editable initial value on systems without 
readline? If a platform-independent version is not practical, I don't 
think there's any point in only half-supporting it.


-- 
Steven


More information about the Python-ideas mailing list