Interactive prompts on the Terminal service (Effect's Prompt).
A prompt is an effect: yield from prompt (or run(prompt)) asks it.
Prompts combine with map, flat_map and all; custom builds
new ones from render / process / clear handlers. Styling comes from the
PromptTheme reference, overridable per prompt with theme=.
Types#
| Type | Definition | Description |
|---|---|---|
Action | type Action[S, O] = Beep | NextFrame[S] | Submit[O] | |
ProcessInput | type ProcessInput[A] = Input | Event[A] | |
PromptEnvironment | type PromptEnvironment = FileSystem | Path | Terminal | The services a prompt runs with (Effect's |
FileType | type FileType = Literal['file', 'directory', 'either'] |
Classes#
Functions#
auto_complete#
auto_complete[A](message, choices, *, max_per_page=10, filter_label='filter', filter_placeholder='type to filter', empty_message='No matches', theme=None) -> Prompt[A]select with a filter: typing narrows the list to titles
containing the text (case-insensitively); Ctrl+N / Ctrl+P / Ctrl+K and
the arrows move, Ctrl+U clears the filter.
| Parameter | Type | Description |
|---|---|---|
message | str | |
choices | Sequence[Choice[A]] | |
max_per_page | int = 10 | |
filter_label | str = 'filter' | |
filter_placeholder | str = 'type to filter' | |
empty_message | str = 'No matches' | |
theme | ThemeOptions | None = None |
Returns Prompt[A]
def auto_complete[A](
message: str,
choices: Sequence[Choice[A]],
*,
max_per_page: int = 10,
filter_label: str = "filter",
filter_placeholder: str = "type to filter",
empty_message: str = "No matches",
theme: ThemeOptions | None = None,
) -> Prompt[A]:
"""``select`` with a filter: typing narrows the list to titles
containing the text (case-insensitively); Ctrl+N / Ctrl+P / Ctrl+K and
the arrows move, Ctrl+U clears the filter."""
handlers = _AutoComplete(
message,
tuple(choices),
max_per_page,
filter_label,
filter_placeholder,
empty_message,
theme,
)
initial = handlers.initial()
return custom(initial, Handlers(handlers.render, handlers.process, handlers.clear))confirm#
confirm(message, *, initial=False, confirm_label='yes', deny_label='no', default_confirm='(Y/n)', default_deny='(y/N)', theme=None) -> Prompt[bool]Yes or no: y / t is yes, n / f is no, Enter takes
initial. The placeholder shows the default; the labels show the
answer.
| Parameter | Type | Description |
|---|---|---|
message | str | |
initial | bool = False | |
confirm_label | str = 'yes' | |
deny_label | str = 'no' | |
default_confirm | str = '(Y/n)' | |
default_deny | str = '(y/N)' | |
theme | ThemeOptions | None = None |
Returns Prompt[bool]
def confirm(
message: str,
*,
initial: bool = False,
confirm_label: str = "yes",
deny_label: str = "no",
default_confirm: str = "(Y/n)",
default_deny: str = "(y/N)",
theme: ThemeOptions | None = None,
) -> Prompt[bool]:
"""Yes or no: ``y`` / ``t`` is yes, ``n`` / ``f`` is no, Enter takes
``initial``. The placeholder shows the default; the labels show the
answer."""
opts = _Confirm(
message, initial, confirm_label, deny_label, default_confirm, default_deny, theme
)
def render(state: bool, action: Action[bool, bool]) -> Effect[str]:
def body():
figures = yield from get_theme(opts.theme)
match action:
case Beep():
return ansi.beep
case NextFrame():
leading = annotate_symbol(figures, figures.prefix, figures.primary_color)
trailing = annotate_symbol(figures, figures.pointer_small, figures.muted_color)
placeholder = opts.default_confirm if action.state else opts.default_deny
styled = ansi.annotate(figures.colors, placeholder, figures.muted_color)
return ansi.cursor_hide + render_prompt(
styled, opts.message, leading, trailing, figures
)
case Submit():
leading = annotate_symbol(figures, figures.tick, figures.success_color)
trailing = annotate_symbol(figures, figures.ellipsis, figures.muted_color)
label = opts.confirm_label if action.value else opts.deny_label
return render_prompt(label, opts.message, leading, trailing, figures) + "\n"
return gen(body)
def process(input: UserInput, state: bool) -> Effect[Action[bool, bool]]:
value = (input.input or "").lower()
if input.key.name in ("enter", "return"):
return succeed(Submit(opts.initial))
if _TRUE.search(value):
return succeed(Submit(True))
if _FALSE.search(value):
return succeed(Submit(False))
return succeed(Beep())
def clear(state: bool, action: Action[bool, bool]):
def body():
columns = yield from terminal_columns()
figures = yield from get_theme(opts.theme)
placeholder = opts.default_confirm if state else opts.default_deny
text = render_prompt(
placeholder,
opts.message,
figures.prefix,
figures.pointer_small,
figures,
plain=True,
)
return erase_text(text, columns) + reset_current_line()
return gen(body)
return custom(initial, Handlers(render, process, clear))toggle#
toggle(message, *, initial=False, active='on', inactive='off', theme=None) -> Prompt[bool]A switch between active and inactive: arrows, j / k,
0 / 1, Space or Tab change it; Enter submits.
| Parameter | Type | Description |
|---|---|---|
message | str | |
initial | bool = False | |
active | str = 'on' | |
inactive | str = 'off' | |
theme | ThemeOptions | None = None |
Returns Prompt[bool]
def toggle(
message: str,
*,
initial: bool = False,
active: str = "on",
inactive: str = "off",
theme: ThemeOptions | None = None,
) -> Prompt[bool]:
"""A switch between ``active`` and ``inactive``: arrows, ``j`` / ``k``,
``0`` / ``1``, Space or Tab change it; Enter submits."""
opts = _Toggle(message, initial, active, inactive, theme)
def render_toggle(value: bool, figures: Theme, submitted: bool) -> str:
separator = annotate_symbol(figures, figures.toggle_separator, figures.muted_color)
selected = (
ansi.underlined,
figures.submitted_color if submitted else figures.primary_color,
)
inactive_text = (
opts.inactive if value else ansi.annotate(figures.colors, opts.inactive, *selected)
)
active_text = (
ansi.annotate(figures.colors, opts.active, *selected) if value else opts.active
)
return active_text + " " + separate_symbol(separator, inactive_text)
def render(state: bool, action: Action[bool, bool]) -> Effect[str]:
def body():
figures = yield from get_theme(opts.theme)
match action:
case Beep():
return ansi.beep
case NextFrame():
leading = annotate_symbol(figures, figures.prefix, figures.primary_color)
trailing = annotate_symbol(figures, figures.pointer_small, figures.muted_color)
text = render_toggle(state, figures, False)
return ansi.cursor_hide + render_prompt(
text, opts.message, leading, trailing, figures
)
case Submit():
leading = annotate_symbol(figures, figures.tick, figures.success_color)
trailing = annotate_symbol(figures, figures.ellipsis, figures.muted_color)
text = render_toggle(state, figures, True)
return render_prompt(text, opts.message, leading, trailing, figures) + "\n"
return gen(body)
def process(input: UserInput, state: bool) -> Effect[Action[bool, bool]]:
match input.key.name:
case "0" | "j" | "delete" | "right" | "down":
return succeed(NextFrame(False))
case "1" | "k" | "left" | "up":
return succeed(NextFrame(True))
case " " | "tab":
return succeed(NextFrame(not state))
case "enter" | "return":
return succeed(Submit(state))
case _:
return succeed(Beep())
def clear(state: bool, action: Action[bool, bool]):
def body():
columns = yield from terminal_columns()
figures = yield from get_theme(opts.theme)
text = opts.active + " " + separate_symbol(figures.toggle_separator, opts.inactive)
line = render_prompt(
text, opts.message, figures.prefix, figures.pointer_small, figures, plain=True
)
return erase_text(line, columns) + reset_current_line()
return gen(body)
return custom(initial, Handlers(render, process, clear))all#
all[A](prompts: Mapping[str, Prompt[A]], /) -> Prompt[dict[str, A]]
all[A](prompts: Iterable[Prompt[A]], /) -> Prompt[list[A]]Ask each prompt in order: a mapping gives a dict by key, an iterable a list.
| Parameter | Type | Description |
|---|---|---|
prompts |
@overload
def all[A](prompts: Mapping[str, Prompt[A]], /) -> Prompt[dict[str, A]]: ...
@overload
def all[A](prompts: Iterable[Prompt[A]], /) -> Prompt[list[A]]: ...
def all(prompts: Mapping[str, Prompt[Any]] | Iterable[Prompt[Any]], /) -> Prompt[Any]:
"""Ask each prompt in order: a mapping gives a dict by key, an iterable
a list."""
if isinstance(prompts, Mapping):
entries = list(cast("Mapping[str, Prompt[Any]]", prompts).items())
result: Prompt[dict[str, Any]] = _Succeed({})
for key, prompt in entries:
result = result.flat_map(_add_entry(key, prompt))
return result
items: Prompt[list[Any]] = _Succeed([])
for prompt in prompts:
items = items.flat_map(_append(prompt))
return itemscustom#
custom[S, O](initial: S | Effect[S, Never, PromptEnvironment], handlers: Handlers[S, O, UserInput], /) -> Prompt[O]
custom[S, O, X](initial: S | Effect[S, Never, PromptEnvironment], events: Dequeue[X, Any], handlers: Handlers[S, O, ProcessInput[X]], /) -> Prompt[O]A prompt from handlers starting at initial (or the state an
effect gives); with an events queue, process gets Input and
Event values.
| Parameter | Type | Description |
|---|---|---|
initial | ||
args | = () |
@overload
def custom[S, O](
initial: S | Effect[S, Never, PromptEnvironment], handlers: Handlers[S, O, UserInput], /
) -> Prompt[O]: ...
@overload
def custom[S, O, X](
initial: S | Effect[S, Never, PromptEnvironment],
events: Dequeue[X, Any],
handlers: Handlers[S, O, ProcessInput[X]],
/,
) -> Prompt[O]: ...
def custom(initial: Any, *args: Any) -> Prompt[Any]:
"""A prompt from ``handlers`` starting at ``initial`` (or the state an
effect gives); with an ``events`` queue, ``process`` gets ``Input`` and
``Event`` values."""
if len(args) == 1:
return _Loop[Any, Any, Any](initial, args[0], None)
return _Loop[Any, Any, Any](initial, args[1], args[0])make_theme#
make_theme(**options) -> ThemeThe default theme (Windows symbols on Windows) with options;
colors defaults to whether stdout is a terminal and NO_COLOR is
unset.
| Parameter | Type | Description |
|---|---|---|
options | Unpack[ThemeOptions] = {} |
Returns Theme
def make_theme(**options: Unpack[ThemeOptions]) -> Theme:
"""The default theme (Windows symbols on Windows) with ``options``;
``colors`` defaults to whether stdout is a terminal and ``NO_COLOR`` is
unset."""
base = Theme(**_WINDOWS) if sys.platform == "win32" else Theme()
theme = replace(base, **options)
return theme if "colors" in options else replace(theme, colors=ansi.detect_colors())run#
run[A](prompt) -> Effect[A, QuitError, PromptEnvironment]Ask: render, read key presses until the prompt submits. Fails with
QuitError when input ends (Ctrl+C, Ctrl+D).
| Parameter | Type | Description |
|---|---|---|
prompt | Prompt[A] |
Returns Effect[A, QuitError, PromptEnvironment]
def run[A](prompt: Prompt[A]) -> Effect[A, QuitError, PromptEnvironment]:
"""Ask: render, read key presses until the prompt submits. Fails with
``QuitError`` when input ends (Ctrl+C, Ctrl+D)."""
def body():
terminal = yield from Terminal()
input = yield from terminal.read_input.cached()
return (yield from prompt.run_with(terminal, input))
return scoped(gen(body)).map_error(lambda _: QuitError())prompt_succeed#
prompt_succeed[A](value) -> Prompt[A]A prompt that asks nothing and gives value.
| Parameter | Type | Description |
|---|---|---|
value | A |
Returns Prompt[A]
def prompt_succeed[A](value: A) -> Prompt[A]:
"""A prompt that asks nothing and gives ``value``."""
return _Succeed(value)date#
date(message, *, initial=None, date_mask='YYYY-MM-DD HH:mm:ss', validate=succeed, locales=None, theme=None) -> Prompt[datetime]A date and time, shown through date_mask. Left / Right and Tab
move between fields, the arrows or j / k step the field, digits
type into it; Enter submits once validate accepts the value. Gives
an aware datetime in the local time zone (naive initial values are
read as local time).
| Parameter | Type | Description |
|---|---|---|
message | str | |
initial | datetime | None = None | |
date_mask | str = 'YYYY-MM-DD HH:mm:ss' | |
validate | Validate = succeed | |
locales | Locales | None = None | |
theme | ThemeOptions | None = None |
Returns Prompt[datetime]
def date(
message: str,
*,
initial: datetime | None = None,
date_mask: str = "YYYY-MM-DD HH:mm:ss",
validate: Validate = succeed,
locales: Locales | None = None,
theme: ThemeOptions | None = None,
) -> Prompt[datetime]:
"""A date and time, shown through ``date_mask``. Left / Right and Tab
move between fields, the arrows or ``j`` / ``k`` step the field, digits
type into it; Enter submits once ``validate`` accepts the value. Gives
an aware datetime in the local time zone (naive ``initial`` values are
read as local time)."""
start = (initial or datetime.now()).astimezone().replace(tzinfo=None) # noqa: DTZ005 local time
handlers = _DatePrompt(message, start, date_mask, validate, locales or Locales(), theme)
return custom(
sync(handlers.initial), Handlers(handlers.render, handlers.process, handlers.clear)
)file#
file(*, type='file', message='Choose a file', starting_path=None, default=None, max_per_page=10, filter=lambda _: True, theme=None) -> Prompt[str]A path chosen by browsing: typing filters the listing, Enter opens a
directory or takes a file. With type="directory" or "either" a
directory with contents asks whether to open it (y) or take it
(n).
| Parameter | Type | Description |
|---|---|---|
type | FileType = 'file' | |
message | str = 'Choose a file' | |
starting_path | str | None = None | |
default | str | None = None | |
max_per_page | int = 10 | |
filter | Callable[[str], bool | Effect[bool, Never, PromptEnvironment]] = lambda _: True | |
theme | ThemeOptions | None = None |
Returns Prompt[str]
def file(
*,
type: FileType = "file",
message: str = "Choose a file",
starting_path: str | None = None,
default: str | None = None,
max_per_page: int = 10,
filter: Callable[[str], bool | Effect[bool, Never, PromptEnvironment]] = lambda _: True,
theme: ThemeOptions | None = None,
) -> Prompt[str]:
"""A path chosen by browsing: typing filters the listing, Enter opens a
directory or takes a file. With ``type="directory"`` or ``"either"`` a
directory with contents asks whether to open it (``y``) or take it
(``n``)."""
handlers = _FilePrompt(
_Options(type, message, starting_path, default, max_per_page, filter, theme)
)
return custom(handlers.initial(), Handlers(handlers.render, handlers.process, handlers.clear))multi_select#
multi_select[A](choices, *, message=None, max_per_page=10, select_all='Select All', select_none='Select None', inverse_selection='Inverse Selection', min=None, max=None, theme=None) -> Prompt[list[A]]Any number of choices, toggled with Space; the first two rows
select all (or none) and invert the selection. Enter submits once the
count is within min / max.
| Parameter | Type | Description |
|---|---|---|
choices | Sequence[Choice[A]] | |
message | str | None = None | |
max_per_page | int = 10 | |
select_all | str = 'Select All' | |
select_none | str = 'Select None' | |
inverse_selection | str = 'Inverse Selection' | |
min | int | None = None | |
max | int | None = None | |
theme | ThemeOptions | None = None |
Returns Prompt[list[A]]
def multi_select[A](
choices: Sequence[Choice[A]],
*,
message: str | None = None,
max_per_page: int = 10,
select_all: str = "Select All",
select_none: str = "Select None",
inverse_selection: str = "Inverse Selection",
min: int | None = None,
max: int | None = None,
theme: ThemeOptions | None = None,
) -> Prompt[list[A]]:
"""Any number of ``choices``, toggled with Space; the first two rows
select all (or none) and invert the selection. Enter submits once the
count is within ``min`` / ``max``."""
handlers = _MultiSelect(
tuple(choices),
message,
max_per_page,
select_all,
select_none,
inverse_selection,
min,
max,
theme,
)
initial = frozenset(
i for i, choice in enumerate(handlers.choices) if choice.selected and not choice.disabled
)
return custom(_State(0, initial), Handlers(handlers.render, handlers.process, handlers.clear))integer#
integer(message, *, default=None, min=-math.inf, max=math.inf, increment_by=1, decrement_by=1, validate=None, theme=None) -> Prompt[int]An integer, typed or stepped with the arrows (j / k),
starting from default; Enter submits once it is within
min / max (or validate accepts it).
| Parameter | Type | Description |
|---|---|---|
message | str | |
default | int | None = None | |
min | float = -math.inf | |
max | float = math.inf | |
increment_by | int = 1 | |
decrement_by | int = 1 | |
validate | Callable[[int], Effect[int, str]] | None = None | |
theme | ThemeOptions | None = None |
Returns Prompt[int]
def integer(
message: str,
*,
default: int | None = None,
min: float = -math.inf,
max: float = math.inf,
increment_by: int = 1,
decrement_by: int = 1,
validate: Callable[[int], Effect[int, str]] | None = None,
theme: ThemeOptions | None = None,
) -> Prompt[int]:
"""An integer, typed or stepped with the arrows (``j`` / ``k``),
starting from ``default``; Enter submits once it is within
``min`` / ``max`` (or ``validate`` accepts it)."""
handlers = _NumberPrompt(
message,
increment_by,
decrement_by,
validate or _bounds(min, max),
parse_int,
_typed_int,
lambda n: n,
"Must provide an integer value",
theme,
)
return handlers.prompt("" if default is None else str(default))number#
number(message, *, default=None, min=-math.inf, max=math.inf, increment_by=1, decrement_by=1, precision=2, validate=None, theme=None) -> Prompt[float]integer for any number, rounded to precision decimals when
submitted.
| Parameter | Type | Description |
|---|---|---|
message | str | |
default | float | None = None | |
min | float = -math.inf | |
max | float = math.inf | |
increment_by | float = 1 | |
decrement_by | float = 1 | |
precision | int = 2 | |
validate | Callable[[float], Effect[float, str]] | None = None | |
theme | ThemeOptions | None = None |
Returns Prompt[float]
def number(
message: str,
*,
default: float | None = None,
min: float = -math.inf,
max: float = math.inf,
increment_by: float = 1,
decrement_by: float = 1,
precision: int = 2,
validate: Callable[[float], Effect[float, str]] | None = None,
theme: ThemeOptions | None = None,
) -> Prompt[float]:
"""``integer`` for any number, rounded to ``precision`` decimals when
submitted."""
handlers = _NumberPrompt(
message,
float(increment_by),
float(decrement_by),
validate or _bounds(min, max),
parse_float,
_typed_float,
lambda n: _js_round(n, precision),
"Must provide a floating point value",
theme,
)
return handlers.prompt("" if default is None else js_number(default))select#
select[A](choices, *, message=None, max_per_page=10, theme=None) -> Prompt[A]One of choices: arrows or j / k move, Tab cycles, Enter
takes the highlighted one unless it is disabled. Without message
only the list shows.
| Parameter | Type | Description |
|---|---|---|
choices | Sequence[Choice[A]] | |
message | str | None = None | |
max_per_page | int = 10 | |
theme | ThemeOptions | None = None |
Returns Prompt[A]
def select[A](
choices: Sequence[Choice[A]],
*,
message: str | None = None,
max_per_page: int = 10,
theme: ThemeOptions | None = None,
) -> Prompt[A]:
"""One of ``choices``: arrows or ``j`` / ``k`` move, Tab cycles, Enter
takes the highlighted one unless it is disabled. Without ``message``
only the list shows."""
handlers = _Select(tuple(choices), message, max_per_page, theme)
initial = initial_index(handlers.choices)
return custom(initial, Handlers(handlers.render, handlers.process, handlers.clear))hidden#
hidden(message, *, default='', validate=succeed, theme=None) -> Prompt[Redacted[str]]string, not shown at all and given as a Redacted.
| Parameter | Type | Description |
|---|---|---|
message | str | |
default | str = '' | |
validate | Validate[str] = succeed | |
theme | ThemeOptions | None = None |
Returns Prompt[Redacted[str]]
def hidden(
message: str,
*,
default: str = "",
validate: Validate[str] = succeed,
theme: ThemeOptions | None = None,
) -> Prompt[Redacted[str]]:
"""``string``, not shown at all and given as a ``Redacted``."""
return _text_prompt(message, default, validate, "hidden", theme).map(redacted_.make)list_#
list_(message, *, delimiter=',', default='', validate=succeed, theme=None) -> Prompt[list[str]]string, split at delimiter.
| Parameter | Type | Description |
|---|---|---|
message | str | |
delimiter | str = ',' | |
default | str = '' | |
validate | Validate[str] = succeed | |
theme | ThemeOptions | None = None |
Returns Prompt[list[str]]
def list_(
message: str,
*,
delimiter: str = ",",
default: str = "",
validate: Validate[str] = succeed,
theme: ThemeOptions | None = None,
) -> Prompt[list[str]]:
"""``string``, split at ``delimiter``."""
separator = delimiter or ","
prompt = string(message, default=default, validate=validate, theme=theme)
return prompt.map(lambda text: text.split(separator))password#
password(message, *, default='', validate=succeed, theme=None) -> Prompt[Redacted[str]]string, shown masked and given as a Redacted.
| Parameter | Type | Description |
|---|---|---|
message | str | |
default | str = '' | |
validate | Validate[str] = succeed | |
theme | ThemeOptions | None = None |
Returns Prompt[Redacted[str]]
def password(
message: str,
*,
default: str = "",
validate: Validate[str] = succeed,
theme: ThemeOptions | None = None,
) -> Prompt[Redacted[str]]:
"""``string``, shown masked and given as a ``Redacted``."""
return _text_prompt(message, default, validate, "password", theme).map(redacted_.make)string#
string(message, *, default='', validate=succeed, theme=None) -> Prompt[str]A line of text, starting from default (Tab fills it in when the
input is empty); Enter submits once validate accepts it.
| Parameter | Type | Description |
|---|---|---|
message | str | |
default | str = '' | |
validate | Validate[str] = succeed | |
theme | ThemeOptions | None = None |
Returns Prompt[str]
def string(
message: str,
*,
default: str = "",
validate: Validate[str] = succeed,
theme: ThemeOptions | None = None,
) -> Prompt[str]:
"""A line of text, starting from ``default`` (Tab fills it in when the
input is empty); Enter submits once ``validate`` accepts it."""
return _text_prompt(message, default, validate, "text", theme)