InquirerPrompt 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,286 @@
1
+ """Module contains the class to create a rawlist prompt."""
2
+
3
+ from typing import Any, Callable, List, Optional, Tuple, Union
4
+
5
+ from InquirerPy.base import InquirerPyUIListControl
6
+ from InquirerPy.enum import INQUIRERPY_POINTER_SEQUENCE
7
+ from InquirerPy.exceptions import InvalidArgument
8
+ from InquirerPy.prompts.list import ListPrompt
9
+ from InquirerPy.separator import Separator
10
+ from InquirerPy.utils import (
11
+ InquirerPyDefault,
12
+ InquirerPyKeybindings,
13
+ InquirerPyListChoices,
14
+ InquirerPyMessage,
15
+ InquirerPySessionResult,
16
+ InquirerPyStyle,
17
+ InquirerPyValidate,
18
+ )
19
+
20
+ __all__ = ["RawlistPrompt"]
21
+
22
+
23
+ class InquirerPyRawlistControl(InquirerPyUIListControl):
24
+ """An :class:`~prompt_toolkit.layout.UIControl` class that displays a list of choices.
25
+
26
+ Reference the parameter definition in :class:`.RawlistPrompt`.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ choices: InquirerPyListChoices,
32
+ default: Any,
33
+ pointer: str,
34
+ separator: str,
35
+ marker: str,
36
+ session_result: Optional[InquirerPySessionResult],
37
+ multiselect: bool,
38
+ marker_pl: str,
39
+ ) -> None:
40
+ self._pointer = pointer
41
+ self._separator = separator
42
+ self._marker = marker
43
+ self._marker_pl = marker_pl
44
+ super().__init__(
45
+ choices=choices,
46
+ default=default,
47
+ session_result=session_result,
48
+ multiselect=multiselect,
49
+ )
50
+
51
+ def _format_choices(self) -> None:
52
+ separator_count = 0
53
+ for index, choice in enumerate(self.choices):
54
+ if isinstance(choice["value"], Separator):
55
+ separator_count += 1
56
+ continue
57
+ choice["display_index"] = index + 1 - separator_count
58
+ choice["actual_index"] = index
59
+
60
+ if self.choices:
61
+ first_valid_choice_index = 0
62
+ while isinstance(
63
+ self.choices[first_valid_choice_index]["value"], Separator
64
+ ):
65
+ first_valid_choice_index += 1
66
+ if self.selected_choice_index == first_valid_choice_index:
67
+ for choice in self.choices:
68
+ if isinstance(choice["value"], Separator):
69
+ continue
70
+ if choice["display_index"] == self._default:
71
+ self.selected_choice_index = choice["actual_index"]
72
+ break
73
+
74
+ def _get_hover_text(self, choice) -> List[Tuple[str, str]]:
75
+ display_choices = []
76
+ display_choices.append(("class:pointer", self._pointer))
77
+ display_choices.append(
78
+ (
79
+ "class:marker",
80
+ self._marker if choice["enabled"] else self._marker_pl,
81
+ )
82
+ )
83
+ if not isinstance(choice["value"], Separator):
84
+ display_choices.append(
85
+ (
86
+ "class:pointer",
87
+ "%s%s" % (str(choice["display_index"]), self._separator),
88
+ )
89
+ )
90
+ display_choices.append(("[SetCursorPosition]", ""))
91
+ display_choices.append(("class:pointer", choice["name"]))
92
+ return display_choices
93
+
94
+ def _get_normal_text(self, choice) -> List[Tuple[str, str]]:
95
+ display_choices = []
96
+ display_choices.append(("", len(self._pointer) * " "))
97
+ display_choices.append(
98
+ (
99
+ "class:marker",
100
+ self._marker if choice["enabled"] else self._marker_pl,
101
+ )
102
+ )
103
+ if not isinstance(choice["value"], Separator):
104
+ display_choices.append(
105
+ ("", "%s%s" % (str(choice["display_index"]), self._separator))
106
+ )
107
+ display_choices.append(("", choice["name"]))
108
+ else:
109
+ display_choices.append(("class:separator", choice["name"]))
110
+ return display_choices
111
+
112
+
113
+ class RawlistPrompt(ListPrompt):
114
+ """Create a prompt that displays a list of choices with index number as shortcuts.
115
+
116
+ A wrapper class around :class:`~prompt_toolkit.application.Application`.
117
+
118
+ Each choice will have an index number infront of them with keybinding created for that index number.
119
+ Enables user to use number to jump to different choices using number.
120
+
121
+ Args:
122
+ message: The question to ask the user.
123
+ Refer to :ref:`pages/dynamic:message` documentation for more details.
124
+ choices: List of choices to display and select.
125
+ Refer to :ref:`pages/prompts/rawlist:Choices` documentation for more details.
126
+ style: An :class:`InquirerPyStyle` instance.
127
+ Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details.
128
+ vi_mode: Use vim keybinding for the prompt.
129
+ Refer to :ref:`pages/kb:Keybindings` documentation for more details.
130
+ default: Set the default value of the prompt.
131
+ This will be used to determine which choice is highlighted (current selection),
132
+ The default value should be the value of one of the choices.
133
+ For :class:`.RawlistPrompt` specifically, default value can also be value between 0-9.
134
+ Refer to :ref:`pages/dynamic:default` documentation for more details.
135
+ separator: Separator symbol. Custom symbol that will be used as a separator between the choice index number and the choices.
136
+ qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.
137
+ amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.
138
+ pointer: Pointer symbol. Customer symbol that will be used to indicate the current choice selection.
139
+ instruction: Short instruction to display next to the question.
140
+ long_instruction: Long instructions to display at the bottom of the prompt.
141
+ validate: Add validation to user input.
142
+ The main use case for this prompt would be when `multiselect` is True, you can enforce a min/max selection.
143
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
144
+ invalid_message: Error message to display when user input is invalid.
145
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
146
+ transformer: A function which performs additional transformation on the value that gets printed to the terminal.
147
+ Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
148
+ Refer to :ref:`pages/dynamic:transformer` documentation for more details.
149
+ filter: A function which performs additional transformation on the result.
150
+ This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
151
+ Refer to :ref:`pages/dynamic:filter` documentation for more details.
152
+ height: Preferred height of the prompt.
153
+ Refer to :ref:`pages/height:Height` documentation for more details.
154
+ max_height: Max height of the prompt.
155
+ Refer to :ref:`pages/height:Height` documentation for more details.
156
+ multiselect: Enable multi-selection on choices.
157
+ You can use `validate` parameter to control min/max selections.
158
+ Setting to True will also change the result from a single value to a list of values.
159
+ marker: Marker Symbol. Custom symbol to indicate if a choice is selected.
160
+ This will take effects when `multiselect` is True.
161
+ marker_pl: Marker place holder when the choice is not selected.
162
+ This is empty space by default.
163
+ border: Create border around the choice window.
164
+ keybindings: Customise the builtin keybindings.
165
+ Refer to :ref:`pages/kb:Keybindings` for more details.
166
+ show_cursor: Display cursor at the end of the prompt.
167
+ Set to False to hide the cursor.
168
+ cycle: Return to top item if hit bottom during navigation or vice versa.
169
+ wrap_lines: Soft wrap question lines when question exceeds the terminal width.
170
+ raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
171
+ will be `None` and the question is skiped.
172
+ mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped.
173
+ mandatory_message: Error message to show when user attempts to skip mandatory prompt.
174
+ session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
175
+
176
+ Examples:
177
+ >>> from InquirerPy import inquirer
178
+ >>> result = inquirer.rawlist(message="Select one:", choices=[1, 2, 3]).execute()
179
+ >>> print(result)
180
+ 1
181
+ """
182
+
183
+ def __init__(
184
+ self,
185
+ message: InquirerPyMessage,
186
+ choices: InquirerPyListChoices,
187
+ default: InquirerPyDefault = None,
188
+ separator: str = ") ",
189
+ style: Optional[InquirerPyStyle] = None,
190
+ vi_mode: bool = False,
191
+ qmark: str = "?",
192
+ amark: str = "?",
193
+ pointer: str = " ",
194
+ instruction: str = "",
195
+ long_instruction: str = "",
196
+ transformer: Optional[Callable[[Any], Any]] = None,
197
+ filter: Optional[Callable[[Any], Any]] = None,
198
+ height: Optional[Union[int, str]] = None,
199
+ max_height: Optional[Union[int, str]] = None,
200
+ multiselect: bool = False,
201
+ marker: str = INQUIRERPY_POINTER_SEQUENCE,
202
+ marker_pl: str = " ",
203
+ border: bool = False,
204
+ validate: Optional[InquirerPyValidate] = None,
205
+ invalid_message: str = "Invalid input",
206
+ keybindings: Optional[InquirerPyKeybindings] = None,
207
+ show_cursor: bool = True,
208
+ cycle: bool = True,
209
+ wrap_lines: bool = True,
210
+ raise_keyboard_interrupt: bool = True,
211
+ mandatory: bool = True,
212
+ mandatory_message: str = "Mandatory prompt",
213
+ session_result: Optional[InquirerPySessionResult] = None,
214
+ ) -> None:
215
+ self.content_control = InquirerPyRawlistControl(
216
+ choices=choices,
217
+ default=default,
218
+ pointer=pointer,
219
+ separator=separator,
220
+ marker=marker,
221
+ session_result=session_result,
222
+ multiselect=multiselect,
223
+ marker_pl=marker_pl,
224
+ )
225
+ super().__init__(
226
+ message=message,
227
+ choices=choices,
228
+ style=style,
229
+ border=border,
230
+ vi_mode=vi_mode,
231
+ qmark=qmark,
232
+ amark=amark,
233
+ instruction=instruction,
234
+ long_instruction=long_instruction,
235
+ transformer=transformer,
236
+ filter=filter,
237
+ height=height,
238
+ max_height=max_height,
239
+ multiselect=multiselect,
240
+ validate=validate,
241
+ invalid_message=invalid_message,
242
+ keybindings=keybindings,
243
+ show_cursor=show_cursor,
244
+ cycle=cycle,
245
+ wrap_lines=wrap_lines,
246
+ raise_keyboard_interrupt=raise_keyboard_interrupt,
247
+ mandatory=mandatory,
248
+ mandatory_message=mandatory_message,
249
+ session_result=session_result,
250
+ )
251
+
252
+ def _on_rendered(self, _) -> None:
253
+ """Override this method to apply custom keybindings.
254
+
255
+ Needs to creat these kb in the callback due to `after_render`
256
+ retrieve the choices asynchronously.
257
+
258
+ Check if fetched choices exceed the limit of 9, raise
259
+ InvalidArgument exception.
260
+ """
261
+
262
+ def keybinding_factory(choice):
263
+ @self.register_kb(str(choice["display_index"]))
264
+ def keybinding(_) -> None:
265
+ self.content_control.selected_choice_index = int(choice["actual_index"])
266
+
267
+ return keybinding
268
+
269
+ if self.content_control.choice_count >= 10:
270
+ raise InvalidArgument("rawlist argument choices cannot exceed length of 9")
271
+
272
+ for choice in self.content_control.choices:
273
+ if not isinstance(choice["value"], Separator):
274
+ keybinding_factory(choice)
275
+
276
+ def _get_prompt_message(self) -> List[Tuple[str, str]]:
277
+ """Return the formatted text to display in the prompt.
278
+
279
+ Overriding this method to allow multiple formatted class to be displayed.
280
+ """
281
+ display_message = super()._get_prompt_message()
282
+ if not self.status["answered"] and self.content_control.choices:
283
+ display_message.append(
284
+ ("class:input", str(self.content_control.selection["display_index"]))
285
+ )
286
+ return display_message
@@ -0,0 +1,137 @@
1
+ """Module contains the class to create a secret prompt."""
2
+
3
+ from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple
4
+
5
+ from InquirerPy.prompts.input import InputPrompt
6
+ from InquirerPy.utils import (
7
+ InquirerPyDefault,
8
+ InquirerPyKeybindings,
9
+ InquirerPyMessage,
10
+ InquirerPySessionResult,
11
+ InquirerPyStyle,
12
+ InquirerPyValidate,
13
+ )
14
+
15
+ if TYPE_CHECKING:
16
+ from prompt_toolkit.input.base import Input
17
+ from prompt_toolkit.output.base import Output
18
+
19
+ __all__ = ["SecretPrompt"]
20
+
21
+
22
+ class SecretPrompt(InputPrompt):
23
+ """Create a text prompt which transforms the input to asterisks while typing.
24
+
25
+ A wrapper class around :class:`~prompt_toolkit.shortcuts.PromptSession`.
26
+
27
+ Args:
28
+ message: The question to ask the user.
29
+ Refer to :ref:`pages/dynamic:message` documentation for more details.
30
+ style: An :class:`InquirerPyStyle` instance.
31
+ Refer to :ref:`Style <pages/style:Alternate Syntax>` documentation for more details.
32
+ vi_mode: Use vim keybinding for the prompt.
33
+ Refer to :ref:`pages/kb:Keybindings` documentation for more details.
34
+ default: Set the default text value of the prompt.
35
+ Refer to :ref:`pages/dynamic:default` documentation for more details.
36
+ qmark: Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.
37
+ amark: Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.
38
+ instruction: Short instruction to display next to the question.
39
+ long_instruction: Long instructions to display at the bottom of the prompt.
40
+ validate: Add validation to user input.
41
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
42
+ invalid_message: Error message to display when user input is invalid.
43
+ Refer to :ref:`pages/validator:Validator` documentation for more details.
44
+ transformer: A function which performs additional transformation on the value that gets printed to the terminal.
45
+ Different than `filter` parameter, this is only visual effect and won’t affect the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
46
+ Refer to :ref:`pages/dynamic:transformer` documentation for more details.
47
+ filter: A function which performs additional transformation on the result.
48
+ This affects the actual value returned by :meth:`~InquirerPy.base.simple.BaseSimplePrompt.execute`.
49
+ Refer to :ref:`pages/dynamic:filter` documentation for more details.
50
+ keybindings: Customise the builtin keybindings.
51
+ Refer to :ref:`pages/kb:Keybindings` for more details.
52
+ wrap_lines: Soft wrap question lines when question exceeds the terminal width.
53
+ raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
54
+ will be `None` and the question is skiped.
55
+ mandatory: Indicate if the prompt is mandatory. If True, then the question cannot be skipped.
56
+ mandatory_message: Error message to show when user attempts to skip mandatory prompt.
57
+ session_result: Used internally for :ref:`index:Classic Syntax (PyInquirer)`.
58
+ input: Used internally and will be removed in future updates.
59
+ output: Used internally and will be removed in future updates.
60
+
61
+ Examples:
62
+ >>> from InquirerPy import inquirer
63
+ >>> result = inquirer.secret(message="Password:").execute()
64
+ >>> print(f"Password: {result}")
65
+ Password: asdf123
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ message: InquirerPyMessage,
71
+ style: Optional[InquirerPyStyle] = None,
72
+ default: InquirerPyDefault = "",
73
+ qmark: str = "?",
74
+ amark: str = "?",
75
+ instruction: str = "",
76
+ long_instruction: str = "",
77
+ vi_mode: bool = False,
78
+ validate: Optional[InquirerPyValidate] = None,
79
+ invalid_message: str = "Invalid input",
80
+ transformer: Optional[Callable[[str], Any]] = None,
81
+ filter: Optional[Callable[[str], Any]] = None,
82
+ keybindings: Optional[InquirerPyKeybindings] = None,
83
+ wrap_lines: bool = True,
84
+ raise_keyboard_interrupt: bool = True,
85
+ mandatory: bool = True,
86
+ mandatory_message: str = "Mandatory prompt",
87
+ session_result: Optional[InquirerPySessionResult] = None,
88
+ input: Optional["Input"] = None,
89
+ output: Optional["Output"] = None,
90
+ ) -> None:
91
+ super().__init__(
92
+ message=message,
93
+ style=style,
94
+ vi_mode=vi_mode,
95
+ default=default,
96
+ qmark=qmark,
97
+ amark=amark,
98
+ instruction=instruction,
99
+ long_instruction=long_instruction,
100
+ validate=validate,
101
+ invalid_message=invalid_message,
102
+ is_password=True,
103
+ transformer=transformer,
104
+ filter=filter,
105
+ keybindings=keybindings,
106
+ wrap_lines=wrap_lines,
107
+ raise_keyboard_interrupt=raise_keyboard_interrupt,
108
+ mandatory=mandatory,
109
+ mandatory_message=mandatory_message,
110
+ session_result=session_result,
111
+ input=input,
112
+ output=output,
113
+ )
114
+
115
+ def _get_prompt_message(self) -> List[Tuple[str, str]]:
116
+ """Get message to display infront of the input buffer.
117
+
118
+ Args:
119
+ pre_answer: The formatted text to display before answering the question.
120
+ post_answer: The formatted text to display after answering the question.
121
+
122
+ Returns:
123
+ Formatted text in list of tuple format.
124
+ """
125
+ pre_answer = (
126
+ "class:instruction",
127
+ " %s " % self.instruction if self.instruction else " ",
128
+ )
129
+ post_answer = (
130
+ "class:answer",
131
+ (
132
+ ""
133
+ if not self.status["result"]
134
+ else " %s" % "".join(["*" for _ in self.status["result"]])
135
+ ),
136
+ )
137
+ return super()._get_prompt_message(pre_answer, post_answer)
InquirerPy/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561. The InquirerPy package uses inline types.
InquirerPy/resolver.py ADDED
@@ -0,0 +1,220 @@
1
+ """This module contains the classic entrypoint for creating prompts.
2
+
3
+ A `PyInquirer <https://github.com/CITGuru/PyInquirer>`_ compatible entrypoint :func:`.prompt`.
4
+ """
5
+
6
+ from typing import Any, Dict, List, Optional, Tuple, Union
7
+
8
+ from InquirerPy.exceptions import InvalidArgument, RequiredKeyNotFound
9
+ from InquirerPy.prompts.checkbox import CheckboxPrompt
10
+ from InquirerPy.prompts.confirm import ConfirmPrompt
11
+ from InquirerPy.prompts.expand import ExpandPrompt
12
+ from InquirerPy.prompts.filepath import FilePathPrompt
13
+ from InquirerPy.prompts.fuzzy import FuzzyPrompt
14
+ from InquirerPy.prompts.input import InputPrompt
15
+ from InquirerPy.prompts.list import ListPrompt
16
+ from InquirerPy.prompts.number import NumberPrompt
17
+ from InquirerPy.prompts.rawlist import RawlistPrompt
18
+ from InquirerPy.prompts.secret import SecretPrompt
19
+ from InquirerPy.utils import (
20
+ InquirerPyKeybindings,
21
+ InquirerPyQuestions,
22
+ InquirerPySessionResult,
23
+ get_style,
24
+ )
25
+
26
+ __all__ = ["prompt", "prompt_async"]
27
+
28
+ question_mapping = {
29
+ "confirm": ConfirmPrompt,
30
+ "filepath": FilePathPrompt,
31
+ "password": SecretPrompt,
32
+ "input": InputPrompt,
33
+ "list": ListPrompt,
34
+ "checkbox": CheckboxPrompt,
35
+ "rawlist": RawlistPrompt,
36
+ "expand": ExpandPrompt,
37
+ "fuzzy": FuzzyPrompt,
38
+ "number": NumberPrompt,
39
+ }
40
+
41
+
42
+ def _get_questions(questions: InquirerPyQuestions) -> List[Dict[str, Any]]:
43
+ """Process and validate questions.
44
+
45
+ Args:
46
+ questions: List of questions to create prompt.
47
+
48
+ Returns:
49
+ List of validated questions.
50
+ """
51
+ if isinstance(questions, dict):
52
+ questions = [questions]
53
+
54
+ if not isinstance(questions, list):
55
+ raise InvalidArgument("argument questions should be type of list or dictionary")
56
+
57
+ return questions
58
+
59
+
60
+ def _get_question(
61
+ original_question: Dict[str, Any], result: InquirerPySessionResult, index: int
62
+ ) -> Tuple[Optional[Dict[str, Any]], str, Union[str, int], str]:
63
+ """Get information from individual question.
64
+
65
+ Args:
66
+ original_question: Original question dictionary.
67
+ result: Current prompt session result.
68
+ index: Question index.
69
+
70
+ Returns:
71
+ A tuple containing question information in the order of
72
+ question dictionary, type of question, name of question, message of question.
73
+ """
74
+ question = original_question.copy()
75
+ question_type = question.pop("type")
76
+ question_name = question.pop("name", index)
77
+ message = question.pop("message")
78
+ question_when = question.pop("when", None)
79
+ if question_when and not question_when(result):
80
+ result[question_name] = None
81
+ question = None
82
+ return question, question_type, question_name, message
83
+
84
+
85
+ async def prompt_async(
86
+ questions: InquirerPyQuestions,
87
+ style: Optional[Dict[str, str]] = None,
88
+ vi_mode: bool = False,
89
+ raise_keyboard_interrupt: bool = True,
90
+ keybindings: Optional[InquirerPyKeybindings] = None,
91
+ style_override: bool = True,
92
+ ) -> InquirerPySessionResult:
93
+ """Classic syntax entrypoint to create a prompt session via asynchronous method.
94
+
95
+ Refer to :func:`InquirerPy.resolver.prompt` for detailed documentations.
96
+ """
97
+ result: InquirerPySessionResult = {}
98
+ if not keybindings:
99
+ keybindings = {}
100
+
101
+ questions = _get_questions(questions=questions)
102
+ question_style = get_style(style, style_override)
103
+
104
+ for index, original_question in enumerate(questions):
105
+ try:
106
+ question, question_type, question_name, message = _get_question(
107
+ original_question=original_question, result=result, index=index
108
+ )
109
+ if question is None:
110
+ continue
111
+ args = {
112
+ "message": message,
113
+ "style": question_style,
114
+ "vi_mode": vi_mode,
115
+ "raise_keyboard_interrupt": raise_keyboard_interrupt,
116
+ "session_result": result,
117
+ "keybindings": {**keybindings, **question.pop("keybindings", {})},
118
+ }
119
+ result[question_name] = await question_mapping[question_type](
120
+ **args, **question
121
+ ).execute_async()
122
+ except KeyError:
123
+ raise RequiredKeyNotFound
124
+
125
+ return result
126
+
127
+
128
+ def prompt(
129
+ questions: InquirerPyQuestions,
130
+ style: Optional[Dict[str, str]] = None,
131
+ vi_mode: bool = False,
132
+ raise_keyboard_interrupt: bool = True,
133
+ keybindings: Optional[InquirerPyKeybindings] = None,
134
+ style_override: bool = True,
135
+ ) -> InquirerPySessionResult:
136
+ """Classic syntax entrypoint to create a prompt session.
137
+
138
+ Resolve user provided list of questions, display prompts and get the results.
139
+
140
+ Args:
141
+ questions: A list of :ref:`pages/prompt:question` to ask. Refer to documentation for more info.
142
+ style: A :class:`dict` containing the style specification for the prompt. Refer to :ref:`pages/style:Style` for more info.
143
+ vi_mode: Use vim keybindings for the prompt instead of the default emacs keybindings.
144
+ Refer to :ref:`pages/kb:Keybindings` for more info.
145
+ raise_keyboard_interrupt: Raise the :class:`KeyboardInterrupt` exception when `ctrl-c` is pressed. If false, the result
146
+ will be `None` and the question is skiped.
147
+ keybindings: List of custom :ref:`pages/kb:Keybindings` to apply. Refer to documentation for more info.
148
+ style_override: Override all default styles. When providing any style customisation, all default styles are removed when this is True.
149
+
150
+ Returns:
151
+ A dictionary containing all of the question answers. The key is the name of the question and the value is the
152
+ user answer. If the `name` key is not present as part of the question, then the question index will be used
153
+ as the key.
154
+
155
+ Raises:
156
+ RequiredKeyNotFound: When the question is missing required keys.
157
+ InvalidArgument: When the provided `questions` argument is not a type of :class:`list` nor :class:`dictionary`.
158
+
159
+ Examples:
160
+ >>> from InquirerPy import prompt
161
+ >>> from InquirerPy.validator import NumberValidator
162
+ >>> questions = [
163
+ ... {
164
+ ... "type": "input",
165
+ ... "message": "Enter your age:",
166
+ ... "validate": NumberValidator(),
167
+ ... "invalid_message": "Input should be number.",
168
+ ... "default": "18",
169
+ ... "name": "age",
170
+ ... "filter": lambda result: int(result),
171
+ ... "transformer": lambda result: "Adult" if int(result) >= 18 else "Youth",
172
+ ... },
173
+ ... {
174
+ ... "type": "rawlist",
175
+ ... "message": "What drinks would you like to buy:",
176
+ ... "default": 2,
177
+ ... "choices": lambda result: ["Soda", "Cidr", "Water", "Milk"]
178
+ ... if result["age"] < 18
179
+ ... else ["Wine", "Beer"],
180
+ ... "name": "drink",
181
+ ... },
182
+ ... {
183
+ ... "type": "list",
184
+ ... "message": "Would you like a bag:",
185
+ ... "choices": ["Yes", "No"],
186
+ ... "when": lambda result: result["drink"] in {"Wine", "Beer"},
187
+ ... },
188
+ ... {"type": "confirm", "message": "Confirm?", "default": True},
189
+ ... ]
190
+ >>> result = prompt(questions=questions)
191
+ """
192
+ result: InquirerPySessionResult = {}
193
+ if not keybindings:
194
+ keybindings = {}
195
+
196
+ questions = _get_questions(questions=questions)
197
+ question_style = get_style(style, style_override)
198
+
199
+ for index, original_question in enumerate(questions):
200
+ try:
201
+ question, question_type, question_name, message = _get_question(
202
+ original_question=original_question, result=result, index=index
203
+ )
204
+ if question is None:
205
+ continue
206
+ args = {
207
+ "message": message,
208
+ "style": question_style,
209
+ "vi_mode": vi_mode,
210
+ "raise_keyboard_interrupt": raise_keyboard_interrupt,
211
+ "session_result": result,
212
+ "keybindings": {**keybindings, **question.pop("keybindings", {})},
213
+ }
214
+ result[question_name] = question_mapping[question_type](
215
+ **args, **question
216
+ ).execute()
217
+ except KeyError:
218
+ raise RequiredKeyNotFound
219
+
220
+ return result
@@ -0,0 +1,23 @@
1
+ """Module contains the :class:`.Separator` class."""
2
+
3
+
4
+ class Separator:
5
+ """A non selectable choice that can be used as part of the choices argument in list type prompts.
6
+
7
+ It can be used to create some visual separations between choices in list type prompts.
8
+
9
+ Args:
10
+ line: Content to display as the separator.
11
+
12
+ Example:
13
+ >>> from InquirerPy import inquirer
14
+ >>> choices = [1, 2, Separator(), 3]
15
+ >>> inquirer.select(message="", choices=choices)
16
+ """
17
+
18
+ def __init__(self, line: str = 15 * "-") -> None:
19
+ self._line = line
20
+
21
+ def __str__(self) -> str:
22
+ """Create string representation of `Separator`."""
23
+ return self._line