select

A prompt that displays a list of choices to select.

Example

demo

Classic Syntax (PyInquirer)
from InquirerPy import prompt
from InquirerPy.base.control import Choice
from InquirerPy.separator import Separator


def main():
    questions = [
        {
            "type": "list",
            "message": "Select an action:",
            "choices": ["Upload", "Download", Choice(value=None, name="Exit")],
            "default": None,
        },
        {
            "type": "list",
            "message": "Select regions:",
            "choices": [
                Choice("ap-southeast-2", name="Sydney"),
                Choice("ap-southeast-1", name="Singapore"),
                Separator(),
                "us-east-1",
                "us-east-2",
            ],
            "multiselect": True,
            "transformer": lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected",
            "when": lambda result: result[0] is not None,
        },
    ]

    result = prompt(questions=questions)


if __name__ == "__main__":
    main()
Alternate Syntax
from InquirerPy import inquirer
from InquirerPy.base.control import Choice
from InquirerPy.separator import Separator


def main():
    action = inquirer.select(
        message="Select an action:",
        choices=[
            "Upload",
            "Download",
            Choice(value=None, name="Exit"),
        ],
        default=None,
    ).execute()
    if action:
        region = inquirer.select(
            message="Select regions:",
            choices=[
                Choice("ap-southeast-2", name="Sydney"),
                Choice("ap-southeast-1", name="Singapore"),
                Separator(),
                "us-east-1",
                "us-east-2",
            ],
            multiselect=True,
            transformer=lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected",
        ).execute()


if __name__ == "__main__":
    main()

Choices

See also

choices

Keybindings

See also

keybindings

{
    "answer": [{"key": "enter"}],   # answer the prompt
    "interrupt": [{"key": "c-c"}],  # raise KeyboardInterrupt
    "skip": [{"key": "c-z"}],   # skip the prompt
}

The following dictionary contains the additional keybindings created by this prompt.

{
    "down": [
        {"key": "down"},
        {"key": "c-n"},   # move down
    ],
    "up": [
        {"key": "up"},
        {"key": "c-p"},   # move up
    ],
    "toggle": [
        {"key": "space"},   # toggle choices
    ],
    "toggle-down": [
        {"key": "c-i"},   # toggle choice and move down (tab)
    ],
    "toggle-up": [
        {"key": "s-tab"},   # toggle choice and move up (shift+tab)
    ],
    "toggle-all": [
        {"key": "alt-r"},   # toggle all choices
        {"key": "c-r"},
    ],
    "toggle-all-true": [
        {"key": "alt-a"},   # toggle all choices true
        {"key": "c-a"}.
    ],
    "toggle-all-false": [],   # toggle all choices false
}

When vi_mode is True, the “up” and “down” navigation key will be changed.

{
    "down": [
        {"key": "down"},
        {"key": "j"},
    ],
    "up": [
        {"key": "up"},
        {"key": "k"},
    ],
}

Multiple Selection

See also

Keybindings

You can enable multiple selection on the prompt by configuring the parameter multiselect to True.

You can also have certain choices pre-selected during the mode. The choices to be pre-selected requires to be either an instance of Choice or dict.

The following example will have 1 and 2 pre-selected.

from InquirerPy import inquirer
from InquirerPy.base.control import Choice

choices = [
    Choice(1, enabled=True),
    Choice(2, enabled=True),
    3,
    4,
]

result = inquirer.select(
    message="Selct one:", choices=choices, multiselect=True
).execute()

Default Value

See also

default

The default parameter will be used to determine which choice is highlighted by default.

It should be the value of one of the choices.

If you wish to pre-select certain choices in multiselect mode, you can leverage the enabled parameter/key of each choice.

from InquirerPy.base import Choice

choices = [
    Choice(1, enabled=True),  # enabled by default
    Choice(2)  # not enabled
]

Reference

class InquirerPy.prompts.list.ListPrompt(message, choices, default=None, style=None, vi_mode=False, qmark='?', amark='?', pointer='❯', instruction='', long_instruction='', transformer=None, filter=None, height=None, max_height=None, multiselect=False, marker='❯', marker_pl=' ', border=False, validate=None, invalid_message='Invalid input', keybindings=None, show_cursor=True, cycle=True, wrap_lines=True, raise_keyboard_interrupt=True, mandatory=True, mandatory_message='Mandatory prompt', session_result=None)[source]

Create a prompt that displays a list of choices to select.

A wrapper class around Application.

Parameters
  • message (Union[str, Callable[[InquirerPySessionResult], str]]) – The question to ask the user. Refer to message documentation for more details.

  • choices (Union[Callable[[InquirerPySessionResult], Union[List[Any], List[Choice], List[Dict[str, Any]]]], List[Any], List[Choice], List[Dict[str, Any]]]) – List of choices to display and select. Refer to choices documentation for more details.

  • style (Optional[InquirerPy.utils.InquirerPyStyle]) – An InquirerPyStyle instance. Refer to Style documentation for more details.

  • vi_mode (bool) – Use vim keybinding for the prompt. Refer to keybindings documentation for more details.

  • default (Union[Any, Callable[[InquirerPySessionResult], Any]]) – Set the default value of the prompt. This will be used to determine which choice is highlighted (current selection), The default value should be the value of one of the choices. Refer to default documentation for more details.

  • qmark (str) – Question mark symbol. Custom symbol that will be displayed infront of the question before its answered.

  • amark (str) – Answer mark symbol. Custom symbol that will be displayed infront of the question after its answered.

  • pointer (str) – Pointer symbol. Customer symbol that will be used to indicate the current choice selection.

  • instruction (str) – Short instruction to display next to the question.

  • long_instruction (str) – Long instructions to display at the bottom of the prompt.

  • validate (Optional[Union[Callable[[Any], bool], Validator]]) – Add validation to user input. The main use case for this prompt would be when multiselect is True, you can enforce a min/max selection. Refer to Validator documentation for more details.

  • invalid_message (str) – Error message to display when user input is invalid. Refer to Validator documentation for more details.

  • transformer (Optional[Callable[[Any], Any]]) – A function which performs additional transformation on the value that gets printed to the terminal. Different than filter parameter, this is only visual effect and won’t affect the actual value returned by execute(). Refer to transformer documentation for more details.

  • filter (Optional[Callable[[Any], Any]]) – A function which performs additional transformation on the result. This affects the actual value returned by execute(). Refer to filter documentation for more details.

  • height (Optional[Union[int, str]]) – Preferred height of the prompt. Refer to height documentation for more details.

  • max_height (Optional[Union[int, str]]) – Max height of the prompt. Refer to height documentation for more details.

  • multiselect (bool) – Enable multi-selection on choices. You can use validate parameter to control min/max selections. Setting to True will also change the result from a single value to a list of values.

  • marker (str) – Marker Symbol. Custom symbol to indicate if a choice is selected. This will take effects when multiselect is True.

  • marker_pl (str) – Marker place holder when the choice is not selected. This is empty space by default.

  • border (bool) – Create border around the choice window.

  • keybindings (Optional[Dict[str, List[Dict[str, Union[str, FilterOrBool, List[str]]]]]]) – Customise the builtin keybindings. Refer to keybindings for more details.

  • show_cursor (bool) – Display cursor at the end of the prompt. Set to False to hide the cursor.

  • cycle (bool) – Return to top item if hit bottom during navigation or vice versa.

  • wrap_lines (bool) – Soft wrap question lines when question exceeds the terminal width.

  • raise_keyboard_interrupt (bool) – Raise the KeyboardInterrupt exception when ctrl-c is pressed. If false, the result will be None and the question is skiped.

  • mandatory (bool) – Indicate if the prompt is mandatory. If True, then the question cannot be skipped.

  • mandatory_message (str) – Error message to show when user attempts to skip mandatory prompt.

  • session_result (Optional[Dict[Union[str, int], Optional[Union[str, bool, List[Any]]]]]) – Used internally for Classic Syntax (PyInquirer).

Return type

None

Examples

>>> from InquirerPy import inquirer
>>> result = inquirer.select(message="Select one:", choices=[1, 2, 3]).execute()
>>> print(result)
1