CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-inquirerpy

Python port of Inquirer.js providing interactive command-line user interfaces with extensive customization options.

Pending
Overview
Eval results
Files

classic-api.mddocs/

Classic API

PyInquirer-compatible functions supporting question dictionaries and session-based prompting with both synchronous and asynchronous execution.

Capabilities

Prompt Function

Main entry point for creating prompts using question dictionaries, compatible with PyInquirer API.

def prompt(
    questions: InquirerPyQuestions,
    style: Optional[Dict[str, str]] = None,
    vi_mode: bool = False,
    raise_keyboard_interrupt: bool = True,
    keybindings: Optional[InquirerPyKeybindings] = None,
    style_override: bool = True
) -> InquirerPySessionResult

Parameters:

  • questions: List of question dictionaries or single question dictionary
  • style: Style dictionary for prompt customization
  • vi_mode: Enable vim keybindings for all prompts
  • raise_keyboard_interrupt: Handle Ctrl+C behavior
  • keybindings: Global keybinding overrides
  • style_override: Override all default styles when providing custom styles

Returns: Dictionary with question names as keys and user answers as values

Usage Examples:

Basic question flow:

from InquirerPy import prompt

questions = [
    {
        "type": "input",
        "message": "What's your name:",
        "name": "name",
        "default": "Anonymous"
    },
    {
        "type": "confirm", 
        "message": "Do you like Python?",
        "name": "likes_python",
        "default": True
    },
    {
        "type": "list",
        "message": "Choose your favorite framework:",
        "name": "framework",
        "choices": ["Django", "Flask", "FastAPI", "Tornado"]
    }
]

answers = prompt(questions)
print(f"Hello {answers['name']}, framework: {answers['framework']}")

Conditional questions with when:

questions = [
    {
        "type": "confirm",
        "message": "Configure database?",
        "name": "setup_db",
        "default": False
    },
    {
        "type": "list",
        "message": "Choose database:",
        "name": "database",
        "choices": ["PostgreSQL", "MySQL", "SQLite"],
        "when": lambda answers: answers["setup_db"]
    },
    {
        "type": "input",
        "message": "Database host:",
        "name": "db_host", 
        "default": "localhost",
        "when": lambda answers: answers.get("setup_db") and answers.get("database") != "SQLite"
    }
]

result = prompt(questions)

With validation and transformation:

from InquirerPy.validator import NumberValidator

questions = [
    {
        "type": "input",
        "message": "Enter your age:",
        "name": "age",
        "validate": NumberValidator(),
        "invalid_message": "Please enter a valid number",
        "filter": lambda result: int(result),
        "transformer": lambda result: f"{result} years old"
    },
    {
        "type": "rawlist",
        "message": "Choose plan:",
        "name": "plan",
        "choices": lambda answers: ["Basic", "Standard", "Premium"] if answers["age"] >= 18 else ["Student", "Basic"],
        "default": lambda answers: "Premium" if answers["age"] >= 25 else "Basic"
    }
]

answers = prompt(questions)

Async Prompt Function

Asynchronous version of the prompt function for integration with async/await code.

async def prompt_async(
    questions: InquirerPyQuestions,
    style: Optional[Dict[str, str]] = None,
    vi_mode: bool = False,
    raise_keyboard_interrupt: bool = True,
    keybindings: Optional[InquirerPyKeybindings] = None,
    style_override: bool = True
) -> InquirerPySessionResult

Usage Example:

import asyncio
from InquirerPy import prompt_async

async def async_survey():
    questions = [
        {
            "type": "input",
            "message": "Project name:",
            "name": "project_name"
        },
        {
            "type": "checkbox",
            "message": "Select features:",
            "name": "features",
            "choices": ["Authentication", "Database", "API", "Frontend"]
        }
    ]
    
    # Use await with async prompt
    answers = await prompt_async(questions)
    
    # Process answers asynchronously
    await process_project_config(answers)
    
    return answers

# Run the async function
result = asyncio.run(async_survey())

Question Dictionary Structure

Required Fields

  • type: Prompt type string (see prompt types below)
  • message: Question text to display
  • name: Key for storing answer in result dictionary

Optional Fields

  • default: Default value or callable returning default
  • choices: List of choices (for list-type prompts) or callable
  • validate: Validation function or Validator object
  • invalid_message: Error message for validation failures
  • when: Conditional function to determine if question should be asked
  • filter: Function to transform the final answer value
  • transformer: Function to transform the display value
  • keybindings: Question-specific keybinding overrides

Prompt Types Mapping

# Classic type names map to prompt classes
prompt_types = {
    "input": InputPrompt,       # Text input
    "password": SecretPrompt,   # Hidden password input  
    "confirm": ConfirmPrompt,   # Yes/no confirmation
    "list": ListPrompt,         # Single selection list
    "checkbox": CheckboxPrompt, # Multi-selection checkboxes
    "rawlist": RawlistPrompt,   # Numbered list (1-9)
    "expand": ExpandPrompt,     # Expandable key-based choices
    "fuzzy": FuzzyPrompt,       # Fuzzy search selection
    "filepath": FilePathPrompt, # File/directory path input
    "number": NumberPrompt      # Numeric input
}

Global Configuration

Style Customization

# Custom styling for all prompts
custom_style = {
    "question": "#ff0066 bold",
    "answer": "#44aa00 bold", 
    "pointer": "#ff0066 bold",
    "highlighted": "#ff0066 bold",
    "selected": "#00aa44",
    "separator": "#6600ff",
    "instruction": "#999999",
    "text": "#ffffff",
    "disabled": "#666666"
}

questions = [{"type": "input", "message": "Test:", "name": "test"}]
result = prompt(questions, style=custom_style)

Keybinding Overrides

# Global keybinding customization
custom_keybindings = {
    "answer": [{"key": "c-m"}],  # Custom Enter key
    "skip": [{"key": "c-z"}],    # Custom skip key
}

result = prompt(questions, keybindings=custom_keybindings)

Error Handling

Keyboard Interrupt Handling

from InquirerPy import prompt
from InquirerPy.exceptions import InvalidArgument, RequiredKeyNotFound

try:
    # Handle Ctrl+C gracefully
    result = prompt(questions, raise_keyboard_interrupt=False)
    if result is None:
        print("Operation cancelled by user")
    else:
        print(f"Results: {result}")
        
except RequiredKeyNotFound:
    print("Question missing required 'type' or 'message' key")
    
except InvalidArgument as e:
    print(f"Invalid question format: {e}")

Validation Error Handling

def validate_email(email):
    if "@" not in email:
        return "Please enter a valid email address"
    return True

questions = [
    {
        "type": "input",
        "message": "Email:",
        "name": "email", 
        "validate": validate_email
    }
]

# Validation errors are handled automatically
# Invalid input shows error message and re-prompts
result = prompt(questions)

Migration from PyInquirer

InquirerPy maintains backward compatibility with PyInquirer. Most existing code works unchanged:

# This PyInquirer code works in InquirerPy
from InquirerPy import prompt  # Changed import only

questions = [
    {
        'type': 'input',
        'name': 'name', 
        'message': 'Your name:',
    },
    {
        'type': 'list',
        'name': 'theme',
        'message': 'What theme do you want?',
        'choices': ['Theme 1', 'Theme 2', 'Theme 3']
    }
]

answers = prompt(questions)

Notable Differences

  • Editor Prompt: Not supported in InquirerPy
  • Enhanced Features: Better performance, bug fixes, more customization
  • Additional Prompts: fuzzy, filepath, number prompts not in PyInquirer
  • Modern Dependencies: Uses prompt-toolkit 3.x vs PyInquirer's 1.x

Install with Tessl CLI

npx tessl i tessl/pypi-inquirerpy

docs

advanced-prompts.md

classic-api.md

confirmation.md

index.md

selection.md

text-input.md

utilities.md

tile.json