Debian Codegraph @

docs/pages/advanced.rst

raw
1 *****************
2 Advanced Concepts
3 *****************
4
5 This page describes some of the more advanced uses of Questionary.
6
7 Validation
8 ##########
9
10 Many of the prompts support a ``validate`` argument, which allows
11 the answer to be validated before being submitted. A user can not
12 submit an answer if it doesn't pass the validation.
13
14 The example below shows :meth:`~questionary.text` input with
15 a validation:
16
17 .. code-block:: python3
18
19 import questionary
20 from questionary import Validator, ValidationError, prompt
21
22 class NameValidator(Validator):
23 def validate(self, document):
24 if len(document.text) == 0:
25 raise ValidationError(
26 message="Please enter a value",
27 cursor_position=len(document.text),
28 )
29
30 questionary.text("What's your name?", validate=NameValidator).ask()
31
32 In this example, the user can not enter a non empty value. If the
33 prompt is submitted without a value. Questionary will show the error
34 message and reject the submission until the user enters a value.
35
36 Alternatively, we can replace the ``NameValidator`` class with a simple
37 function, as seen below:
38
39 .. code-block:: python3
40
41 import questionary
42
43 print(questionary.text(
44 "What's your name?",
45 validate=lambda text: True if len(text) > 0 else "Please enter a value"
46 ).ask())
47
48 Finally, if we do not care about the error message being displayed, we can omit
49 the error message from the final example to use the default:
50
51 .. code-block:: python3
52
53 import questionary
54
55 print(questionary.text("What's your name?", validate=lambda text: len(text) > 0).ask())
56
57 .. admonition:: example
58 :class: info
59
60 The :meth:`~questionary.checkbox` prompt does not support passing a
61 ``Validator``. See the :ref:`API Reference <api-reference>` for all the prompts which
62 support the ``validate`` parameter.
63
64 A Validation Example using the Password Question
65 ************************************************
66
67 Here we see an example of ``validate`` being used on a
68 :meth:`~questionary.password` prompt to enforce complexity requirements:
69
70 .. code-block:: python3
71
72 import re
73 import questionary
74
75 def password_validator(password):
76
77 if len(password) < 10:
78 return "Password must be at least 10 characters"
79
80 elif re.search("[0-9]", password) is None:
81 return "Password must contain a number"
82
83 elif re.search("[a-z]", password) is None:
84 return "Password must contain an lower-case letter"
85
86 elif re.search("[A-Z]", password) is None:
87 return "Password must contain an upper-case letter"
88
89 else:
90 return True
91
92 print(questionary.password("Enter your password", validate=password_validator).ask())
93
94 Keyboard Interrupts
95 ###################
96
97 Prompts can be invoked in either a 'safe' or 'unsafe' way. The safe way
98 captures keyboard interrupts and handles them by catching the interrupt
99 and returning ``None`` for the asked question. If a question is asked
100 using unsafe functions, the keyboard interrupts are not caught.
101
102 Safe
103 ****
104
105 The following are safe (capture keyboard interrupts):
106
107 * :meth:`~questionary.prompt`;
108
109 * :attr:`~questionary.Form.ask` on :class:`~questionary.Form` (returned by
110 :meth:`~questionary.form`);
111
112 * :attr:`~questionary.Question.ask` on :class:`~questionary.Question`, which
113 is returned by the various prompt functions (e.g. :meth:`~questionary.text`,
114 :meth:`~questionary.checkbox`).
115
116 When a keyboard interrupt is captured, the message ``"Cancelled by user"`` is
117 displayed (or a custom message, if one is given) and ``None`` is returned.
118 Here is an example:
119
120 .. code:: python3
121
122 # Questionary handles keyboard interrupt and returns `None` if the
123 # user hits e.g. `Ctrl+C`
124 prompt(...)
125
126 Unsafe
127 ******
128
129 The following are unsafe (do not catch keyboard interrupts):
130
131 * :meth:`~questionary.unsafe_prompt`;
132
133 * :attr:`~questionary.Form.unsafe_ask` on :class:`~questionary.Form` (returned by
134 :meth:`~questionary.form`);
135
136 * :attr:`~questionary.Question.unsafe_ask` on :class:`~questionary.Question`,
137 which is returned by the various prompt functions (e.g. :meth:`~questionary.text`,
138 :meth:`~questionary.checkbox`).
139
140 As a caller you must handle keyboard interrupts yourself
141 when calling these methods. Here is an example:
142
143 .. code:: python3
144
145 try:
146 unsafe_prompt(...)
147
148 except KeyboardInterrupt:
149 # your chance to handle the keyboard interrupt
150 print("Cancelled by user")
151
152
153 Asynchronous Usage
154 ##################
155
156 If you are running asynchronous code and you want to avoid blocking your
157 async loop, you can ask your questions using ``await``.
158 :class:`questionary.Question` and :class:`questionary.Form` have
159 ``ask_async`` and ``unsafe_ask_async`` methods to invoke the
160 question using :mod:`python:asyncio`:
161
162 .. code-block:: python3
163
164 import questionary
165
166 answer = await questionary.text("What's your name?").ask_async()
167
168 Themes & Styling
169 ################
170
171 You can customize all the colors used for the prompts. Every part of the prompt
172 has an identifier, which you can use to style it. Let's create your own custom
173 style:
174
175 .. code-block:: python3
176
177 from questionary import Style
178
179 custom_style_fancy = Style([
180 ('qmark', 'fg:#673ab7 bold'), # token in front of the question
181 ('question', 'bold'), # question text
182 ('answer', 'fg:#f44336 bold'), # submitted answer text behind the question
183 ('pointer', 'fg:#673ab7 bold'), # pointer used in select and checkbox prompts
184 ('highlighted', 'fg:#673ab7 bold'), # pointed-at choice in select and checkbox prompts
185 ('selected', 'fg:#cc5454'), # style for a selected item of a checkbox
186 ('separator', 'fg:#cc5454'), # separator in lists
187 ('instruction', ''), # user instructions for select, rawselect, checkbox
188 ('text', ''), # plain text
189 ('disabled', 'fg:#858585 italic') # disabled choices for select and checkbox prompts
190 ])
191
192 To use the custom style, you need to pass it to the question as a parameter:
193
194 .. code-block:: python3
195
196 questionary.text("What's your phone number", style=custom_style_fancy).ask()
197
198 .. note::
199
200 Default values will be used for any token types not specified in your custom style.
201
202 Styling Choices in Select & Checkbox Questions
203 **********************************************
204
205 It is also possible to use a list of token tuples as a ``Choice`` title to
206 change how an option is displayed in :class:`questionary.select` and
207 :class:`questionary.checkbox`. Make sure to define any additional styles
208 as part of your custom style definition.
209
210 .. code-block:: python3
211
212 import questionary
213 from questionary import Choice, Style
214
215 custom_style_fancy = questionary.Style([
216 ("highlighted", "bold"), # style for a token which should appear highlighted
217 ])
218
219 choices = [Choice(title=[("class:text", "order a "),
220 ("class:highlighted", "big pizza")])]
221
222 questionary.select(
223 "What do you want to do?",
224 choices=choices,
225 style=custom_style_fancy).ask()
226
227 Conditionally Skip Questions
228 ############################
229
230 Sometimes it is helpful to be able to skip a question based on a condition.
231 To avoid the need for an ``if`` around the question, you can pass the
232 condition when you create the question:
233
234 .. code-block:: python3
235
236 import questionary
237
238 DISABLED = True
239 response = questionary.confirm("Are you amazed?").skip_if(DISABLED, default=True).ask()
240
241 If the condition (in this case ``DISABLED``) is ``True``, the question
242 will be skipped and the default value gets returned, otherwise the user will
243 be prompted as usual and the default value will be ignored.
244
245 .. _question_dictionaries:
246
247 Create Questions from Dictionaries
248 ##################################
249
250 Instead of creating questions using the Python functions, you can also create
251 them using a configuration dictionary:
252
253 .. code-block:: python3
254
255 from questionary import prompt
256
257 questions = [
258 {
259 'type': 'text',
260 'name': 'phone',
261 'message': "What's your phone number",
262 },
263 {
264 'type': 'confirm',
265 'message': 'Do you want to continue?',
266 'name': 'continue',
267 'default': True,
268 }
269 ]
270
271 answers = prompt(questions)
272
273 The questions will be prompted one after another and ``prompt`` will return
274 as soon as all of them are answered. The returned ``answers``
275 will be a dictionary containing the responses, e.g.
276
277 .. code-block:: python3
278
279 {"phone": "0123123", "continue": False}.
280
281 Each configuration dictionary for a question must contain the
282 following keys:
283
284 ``type`` (required)
285 The type of the question.
286
287 ``name`` (required)
288 The name of the question (will be used as key in the
289 ``answers`` dictionary).
290
291 ``message`` (required)
292 Message that will be shown to the user.
293
294 In addition to these required configuration parameters, you can
295 add the following optional parameters:
296
297 ``qmark`` (optional)
298 Question mark to use - defaults to ``?``.
299
300 ``default`` (optional)
301 Preselected value.
302
303 ``choices`` (optional)
304 List of choices (applies when ``'type': 'select'``)
305 or function returning a list of choices.
306
307 ``when`` (optional)
308 Function checking if this question should be shown
309 or skipped (same functionality as :attr:`~questionary.Question.skip_if`).
310
311 ``validate`` (optional)
312 Function or Validator Class performing validation (will
313 be performed in real time as users type).
314
315 ``filter`` (optional)
316 Receive the user input and return the filtered value to be
317 used inside the program.
318
319 Further information can be found at the :class:`questionary.prompt`
320 documentation.
321
322 .. _random_label:
323
324 A Complex Example using a Dictionary Configuration
325 **************************************************
326
327 Questionary allows creating quite complex workflows when combining all of the
328 above concepts:
329
330 .. literalinclude:: ../../examples/advanced_workflow.py
331 :language: python3
332
333
334 The above workflow will show to the user the following prompts:
335
336 1. Yes/No question ``"Would you like the next question?"``.
337
338 2. ``"Name this library?"`` - only shown when the first question is answered
339 with yes.
340
341 3. A question to select an item from a list.
342 4. Free text input if ``"other"`` is selected in step 3.
343
344 Depending on the route the user took, the result will look like the following:
345
346 .. code-block:: python3
347
348 {
349 'conditional_step': False,
350 'second_question': 'Test input' # Free form text
351 }
352
353 .. code-block:: python3
354
355 {
356 'conditional_step': True,
357 'next_question': 'questionary',
358 'second_question': 'Test input' # Free form text
359 }
360
361 You can test this workflow yourself by running the
362 `advanced_workflow.py example <https://github.com/tmbo/questionary/blob/master/examples/advanced_workflow.py>`_.