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.
pip install prompt_toolkit
Python code
25 linesfrom 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
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
- Use `FuzzyCompleter` for fuzzy matching with `from prompt_toolkit.completion import FuzzyCompleter`.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.