1from typing
import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload
3from .
import get_console
4from .console
import Console
5from .text
import Text, TextType
7PromptType = TypeVar(
"PromptType")
8DefaultType = TypeVar(
"DefaultType")
12 """Exception base class for prompt related errors."""
16 """Exception to indicate a response was invalid. Raise this within process_response() to indicate an error
17 and provide an error message.
20 message (Union[str, Text]): Error message.
31 """Ask the user for input until a valid response is received. This is the base class, see one of
32 the concrete classes for examples.
35 prompt (TextType, optional): Prompt text. Defaults to "".
36 console (Console, optional): A Console instance or None to use global console. Defaults to None.
37 password (bool, optional): Enable password input. Defaults to False.
38 choices (List[str], optional): A list of valid choices. Defaults to None.
39 show_default (bool, optional): Show default in prompt. Defaults to True.
40 show_choices (bool, optional): Show choices in prompt. Defaults to True.
43 response_type: type = str
45 validate_error_message =
"[prompt.invalid]Please enter a valid value"
46 illegal_choice_message = (
47 "[prompt.invalid.choice]Please select one of the available options"
51 choices: Optional[List[str]] =
None
55 prompt: TextType =
"",
57 console: Optional[Console] =
None,
58 password: bool =
False,
59 choices: Optional[List[str]] =
None,
60 show_default: bool =
True,
61 show_choices: bool =
True,
70 if choices
is not None:
79 prompt: TextType =
"",
81 console: Optional[Console] =
None,
82 password: bool =
False,
83 choices: Optional[List[str]] =
None,
84 show_default: bool =
True,
85 show_choices: bool =
True,
87 stream: Optional[TextIO] =
None,
88 ) -> Union[DefaultType, PromptType]:
95 prompt: TextType =
"",
97 console: Optional[Console] =
None,
98 password: bool =
False,
99 choices: Optional[List[str]] =
None,
100 show_default: bool =
True,
101 show_choices: bool =
True,
102 stream: Optional[TextIO] =
None,
109 prompt: TextType =
"",
111 console: Optional[Console] =
None,
112 password: bool =
False,
113 choices: Optional[List[str]] =
None,
114 show_default: bool =
True,
115 show_choices: bool =
True,
117 stream: Optional[TextIO] =
None,
119 """Shortcut to construct and run a prompt loop and return the result.
122 >>> filename = Prompt.ask("Enter a filename")
125 prompt (TextType, optional): Prompt text. Defaults to "".
126 console (Console, optional): A Console instance or None to use global console. Defaults to None.
127 password (bool, optional): Enable password input. Defaults to False.
128 choices (List[str], optional): A list of valid choices. Defaults to None.
129 show_default (bool, optional): Show default in prompt. Defaults to True.
130 show_choices (bool, optional): Show choices in prompt. Defaults to True.
131 stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None.
138 show_default=show_default,
139 show_choices=show_choices,
141 return _prompt(default=default, stream=stream)
144 """Turn the supplied default in to a Text instance.
147 default (DefaultType): Default value.
150 Text: Text containing rendering of default value.
152 return Text(f
"({default})",
"prompt.default")
158 default (DefaultType): Default value.
161 Text: Text to display in prompt.
163 prompt = self.
prompt.copy()
168 choices = f
"[{_choices}]"
191 stream: Optional[TextIO] =
None,
193 """Get input from user.
196 console (Console): Console instance.
197 prompt (TextType): Prompt text.
198 password (bool): Enable password entry.
201 str: String from user.
203 return console.input(prompt, password=password, stream=stream)
206 """Check value is in the list of valid choices.
209 value (str): Value entered by user.
212 bool: True if choice was valid, otherwise False.
218 """Process response from user, convert to prompt type.
221 value (str): String typed by user.
224 InvalidResponse: If ``value`` is invalid.
227 PromptType: The value to be returned from ask method.
241 """Called to handle validation error.
244 value (str): String entered by user.
245 error (InvalidResponse): Exception instance the initiated the error.
250 """Hook to display something before the prompt."""
253 def __call__(self, *, stream: Optional[TextIO] =
None) -> PromptType:
258 self, *, default: DefaultType, stream: Optional[TextIO] =
None
259 ) -> Union[PromptType, DefaultType]:
262 def __call__(self, *, default: Any = ..., stream: Optional[TextIO] =
None) -> Any:
263 """Run the prompt loop.
266 default (Any, optional): Optional default value.
269 PromptType: Processed value.
275 if value ==
"" and default != ...:
279 except InvalidResponse
as error:
287 """A prompt that returns a str.
290 >>> name = Prompt.ask("Enter your name")
299 """A prompt that returns an integer.
302 >>> burrito_count = IntPrompt.ask("How many burritos do you want to order")
307 validate_error_message =
"[prompt.invalid]Please enter a valid integer number"
311 """A prompt that returns a float.
314 >>> temperature = FloatPrompt.ask("Enter desired temperature")
318 response_type = float
319 validate_error_message =
"[prompt.invalid]Please enter a number"
323 """A yes / no confirmation prompt.
326 >>> if Confirm.ask("Continue"):
332 validate_error_message =
"[prompt.invalid]Please enter Y or N"
333 choices: List[str] = [
"y",
"n"]
336 """Render the default as (y) or (n) rather than True/False."""
338 return Text(f
"({yes})" if default
else f
"({no})", style=
"prompt.default")
341 """Convert choices to a bool."""
348if __name__ ==
"__main__":
355 ":rocket: Enter a number between [b]1[/b] and [b]10[/b]", default=5
357 if result >= 1
and result <= 10:
359 print(
":pile_of_poo: [prompt.invalid]Number must be between 1 and 10")
360 print(f
"number={result}")
364 "Please enter a password [cyan](must be at least 5 characters)",
367 if len(password) >= 5:
369 print(
"[prompt.invalid]password too short")
370 print(f
"password={password!r}")
372 fruit =
Prompt.ask(
"Enter a fruit", choices=[
"apple",
"orange",
"pear"])
373 print(f
"fruit={fruit!r}")
376 print(
"[b]OK :loudly_crying_face:")
Text render_default(self, DefaultType default)
bool process_response(self, str value)
str validate_error_message
None __init__(self, TextType message)
str get_input(cls, Console console, TextType prompt, bool password, Optional[TextIO] stream=None)
PromptType process_response(self, str value)
Text render_default(self, DefaultType default)
PromptType __call__(self, *Optional[TextIO] stream=None)
Text make_prompt(self, DefaultType default)
bool check_choice(self, str value)
tuple illegal_choice_message
None __init__(self, TextType prompt="", *Optional[Console] console=None, bool password=False, Optional[List[str]] choices=None, bool show_default=True, bool show_choices=True)
None on_validate_error(self, str value, InvalidResponse error)
str validate_error_message