0
# Classic API
1
2
PyInquirer-compatible functions supporting question dictionaries and session-based prompting with both synchronous and asynchronous execution.
3
4
## Capabilities
5
6
### Prompt Function
7
8
Main entry point for creating prompts using question dictionaries, compatible with PyInquirer API.
9
10
```python { .api }
11
def prompt(
12
questions: InquirerPyQuestions,
13
style: Optional[Dict[str, str]] = None,
14
vi_mode: bool = False,
15
raise_keyboard_interrupt: bool = True,
16
keybindings: Optional[InquirerPyKeybindings] = None,
17
style_override: bool = True
18
) -> InquirerPySessionResult
19
```
20
21
**Parameters:**
22
- **questions**: List of question dictionaries or single question dictionary
23
- **style**: Style dictionary for prompt customization
24
- **vi_mode**: Enable vim keybindings for all prompts
25
- **raise_keyboard_interrupt**: Handle Ctrl+C behavior
26
- **keybindings**: Global keybinding overrides
27
- **style_override**: Override all default styles when providing custom styles
28
29
**Returns:** Dictionary with question names as keys and user answers as values
30
31
**Usage Examples:**
32
33
Basic question flow:
34
```python
35
from InquirerPy import prompt
36
37
questions = [
38
{
39
"type": "input",
40
"message": "What's your name:",
41
"name": "name",
42
"default": "Anonymous"
43
},
44
{
45
"type": "confirm",
46
"message": "Do you like Python?",
47
"name": "likes_python",
48
"default": True
49
},
50
{
51
"type": "list",
52
"message": "Choose your favorite framework:",
53
"name": "framework",
54
"choices": ["Django", "Flask", "FastAPI", "Tornado"]
55
}
56
]
57
58
answers = prompt(questions)
59
print(f"Hello {answers['name']}, framework: {answers['framework']}")
60
```
61
62
Conditional questions with `when`:
63
```python
64
questions = [
65
{
66
"type": "confirm",
67
"message": "Configure database?",
68
"name": "setup_db",
69
"default": False
70
},
71
{
72
"type": "list",
73
"message": "Choose database:",
74
"name": "database",
75
"choices": ["PostgreSQL", "MySQL", "SQLite"],
76
"when": lambda answers: answers["setup_db"]
77
},
78
{
79
"type": "input",
80
"message": "Database host:",
81
"name": "db_host",
82
"default": "localhost",
83
"when": lambda answers: answers.get("setup_db") and answers.get("database") != "SQLite"
84
}
85
]
86
87
result = prompt(questions)
88
```
89
90
With validation and transformation:
91
```python
92
from InquirerPy.validator import NumberValidator
93
94
questions = [
95
{
96
"type": "input",
97
"message": "Enter your age:",
98
"name": "age",
99
"validate": NumberValidator(),
100
"invalid_message": "Please enter a valid number",
101
"filter": lambda result: int(result),
102
"transformer": lambda result: f"{result} years old"
103
},
104
{
105
"type": "rawlist",
106
"message": "Choose plan:",
107
"name": "plan",
108
"choices": lambda answers: ["Basic", "Standard", "Premium"] if answers["age"] >= 18 else ["Student", "Basic"],
109
"default": lambda answers: "Premium" if answers["age"] >= 25 else "Basic"
110
}
111
]
112
113
answers = prompt(questions)
114
```
115
116
### Async Prompt Function
117
118
Asynchronous version of the prompt function for integration with async/await code.
119
120
```python { .api }
121
async def prompt_async(
122
questions: InquirerPyQuestions,
123
style: Optional[Dict[str, str]] = None,
124
vi_mode: bool = False,
125
raise_keyboard_interrupt: bool = True,
126
keybindings: Optional[InquirerPyKeybindings] = None,
127
style_override: bool = True
128
) -> InquirerPySessionResult
129
```
130
131
**Usage Example:**
132
```python
133
import asyncio
134
from InquirerPy import prompt_async
135
136
async def async_survey():
137
questions = [
138
{
139
"type": "input",
140
"message": "Project name:",
141
"name": "project_name"
142
},
143
{
144
"type": "checkbox",
145
"message": "Select features:",
146
"name": "features",
147
"choices": ["Authentication", "Database", "API", "Frontend"]
148
}
149
]
150
151
# Use await with async prompt
152
answers = await prompt_async(questions)
153
154
# Process answers asynchronously
155
await process_project_config(answers)
156
157
return answers
158
159
# Run the async function
160
result = asyncio.run(async_survey())
161
```
162
163
## Question Dictionary Structure
164
165
### Required Fields
166
- **type**: Prompt type string (see prompt types below)
167
- **message**: Question text to display
168
- **name**: Key for storing answer in result dictionary
169
170
### Optional Fields
171
- **default**: Default value or callable returning default
172
- **choices**: List of choices (for list-type prompts) or callable
173
- **validate**: Validation function or Validator object
174
- **invalid_message**: Error message for validation failures
175
- **when**: Conditional function to determine if question should be asked
176
- **filter**: Function to transform the final answer value
177
- **transformer**: Function to transform the display value
178
- **keybindings**: Question-specific keybinding overrides
179
180
### Prompt Types Mapping
181
182
```python
183
# Classic type names map to prompt classes
184
prompt_types = {
185
"input": InputPrompt, # Text input
186
"password": SecretPrompt, # Hidden password input
187
"confirm": ConfirmPrompt, # Yes/no confirmation
188
"list": ListPrompt, # Single selection list
189
"checkbox": CheckboxPrompt, # Multi-selection checkboxes
190
"rawlist": RawlistPrompt, # Numbered list (1-9)
191
"expand": ExpandPrompt, # Expandable key-based choices
192
"fuzzy": FuzzyPrompt, # Fuzzy search selection
193
"filepath": FilePathPrompt, # File/directory path input
194
"number": NumberPrompt # Numeric input
195
}
196
```
197
198
## Global Configuration
199
200
### Style Customization
201
202
```python
203
# Custom styling for all prompts
204
custom_style = {
205
"question": "#ff0066 bold",
206
"answer": "#44aa00 bold",
207
"pointer": "#ff0066 bold",
208
"highlighted": "#ff0066 bold",
209
"selected": "#00aa44",
210
"separator": "#6600ff",
211
"instruction": "#999999",
212
"text": "#ffffff",
213
"disabled": "#666666"
214
}
215
216
questions = [{"type": "input", "message": "Test:", "name": "test"}]
217
result = prompt(questions, style=custom_style)
218
```
219
220
### Keybinding Overrides
221
222
```python
223
# Global keybinding customization
224
custom_keybindings = {
225
"answer": [{"key": "c-m"}], # Custom Enter key
226
"skip": [{"key": "c-z"}], # Custom skip key
227
}
228
229
result = prompt(questions, keybindings=custom_keybindings)
230
```
231
232
## Error Handling
233
234
### Keyboard Interrupt Handling
235
236
```python
237
from InquirerPy import prompt
238
from InquirerPy.exceptions import InvalidArgument, RequiredKeyNotFound
239
240
try:
241
# Handle Ctrl+C gracefully
242
result = prompt(questions, raise_keyboard_interrupt=False)
243
if result is None:
244
print("Operation cancelled by user")
245
else:
246
print(f"Results: {result}")
247
248
except RequiredKeyNotFound:
249
print("Question missing required 'type' or 'message' key")
250
251
except InvalidArgument as e:
252
print(f"Invalid question format: {e}")
253
```
254
255
### Validation Error Handling
256
257
```python
258
def validate_email(email):
259
if "@" not in email:
260
return "Please enter a valid email address"
261
return True
262
263
questions = [
264
{
265
"type": "input",
266
"message": "Email:",
267
"name": "email",
268
"validate": validate_email
269
}
270
]
271
272
# Validation errors are handled automatically
273
# Invalid input shows error message and re-prompts
274
result = prompt(questions)
275
```
276
277
## Migration from PyInquirer
278
279
InquirerPy maintains backward compatibility with PyInquirer. Most existing code works unchanged:
280
281
```python
282
# This PyInquirer code works in InquirerPy
283
from InquirerPy import prompt # Changed import only
284
285
questions = [
286
{
287
'type': 'input',
288
'name': 'name',
289
'message': 'Your name:',
290
},
291
{
292
'type': 'list',
293
'name': 'theme',
294
'message': 'What theme do you want?',
295
'choices': ['Theme 1', 'Theme 2', 'Theme 3']
296
}
297
]
298
299
answers = prompt(questions)
300
```
301
302
### Notable Differences
303
- **Editor Prompt**: Not supported in InquirerPy
304
- **Enhanced Features**: Better performance, bug fixes, more customization
305
- **Additional Prompts**: fuzzy, filepath, number prompts not in PyInquirer
306
- **Modern Dependencies**: Uses prompt-toolkit 3.x vs PyInquirer's 1.x