Skip to content

Instantly share code, notes, and snippets.

@kevinlinxc
Last active April 27, 2025 22:42
Show Gist options
  • Save kevinlinxc/7c542e2df5ba2d278363167e38904a82 to your computer and use it in GitHub Desktop.
Save kevinlinxc/7c542e2df5ba2d278363167e38904a82 to your computer and use it in GitHub Desktop.
Make your Python user scripts delightful with `prompt_toolkit`

Make your Python user scripts delightful with prompt_toolkit

When writing Python scripts, I ask for user input all the time. This input often has a fixed set of options, those options are usually not fully listed out to the user, the user has to type them out while making no typos, and then we have to do validation afterwards to make sure they picked something valid.

Recently I discovered the prompt_toolkit Python library, which fixes all this.

The library actually has lots of features, but the one that is relevant is this nice dropdown that lets you pick an item from pre-defined options. It saves time for the end-user and the script writer, and it'll delight anyone seeing it for the first time.

Code example below!

# pip install prompt_toolkit
from prompt_toolkit.validation import Validator
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import FuzzyWordCompleter
def prompt_options(options: list, prompt_text: str) -> str:
option_set = set(options)
validator = Validator.from_callable(
lambda x: x in option_set,
error_message="Invalid option!",
move_cursor_to_end=True
)
completer = FuzzyWordCompleter(options)
session = PromptSession(prompt_text, validator=validator, completer=completer)
return session.prompt(pre_run=session.default_buffer.start_completion)
opts = sorted(["Trombone", "Trumpet", "Mayonnaise", "Saxophone", "Violin", "Piano", "Guitar"])
instrument = prompt_options(opts, "Choose an instrument: ")
print(f"You chose: {instrument}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment