How to Use prompt_toolkit Autocomplete in Python

Demonstrates an interactive command-line prompt with autocomplete using prompt_toolkit's WordCompleter and a mock dataset.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 15 views 0 copies

Requires third-party packages — install first
pip install prompt_toolkit

Python code

25 lines
Python 3.9+
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter

def main():
    """Demo of prompt_toolkit autocomplete with a mock dataset."""
    # A simple mock "database" of programming languages
    languages = [
        "Python", "Java", "JavaScript", "TypeScript", "C++", "C#",
        "Go", "Rust", "Ruby", "PHP", "Swift", "Kotlin", "Scala"
    ]
    
    # Create a completer with the mock data
    completer = WordCompleter(languages, ignore_case=True)
    
    # Interactive prompt with autocomplete (type a few letters, press Tab)
    user_input = prompt("Pick a language: ", completer=completer)
    
    # Display the selection
    if user_input.strip():
        print(f"You selected: {user_input}")
    else:
        print("No input provided.")

if __name__ == "__main__":
    main()

Output

stdout
Pick a language: Py<Tab>
You selected: Python

How it works

The WordCompleter is initialized with a list of candidate words and a flag to ignore case. When the user types partial text and presses Tab, the completer suggests matches from the list. The prompt function from prompt_toolkit renders the input field and handles the completion UI. After the user presses Enter, the returned string contains the typed input, which can be processed further.

Common mistakes

  • Forgetting to install prompt_toolkit via pip — it is a third-party library.
  • Not specifying `ignore_case=True` when case-insensitive completion is desired.
  • Assuming the completer works without user pressing Tab — autocomplete is Tab-triggered.

Variations

  1. Use `FuzzyCompleter` for fuzzy matching with `from prompt_toolkit.completion import FuzzyCompleter`.
  2. Define a custom `Completer` class for dynamic suggestions based on user input.

Real-world use cases

  • Building a CLI tool that guides users with known command names or file paths.
  • Interactive data entry forms where users pick from predefined values like country codes.
  • Shell-style REPL for a domain-specific language with keyword and function name completion.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.