Skip to content

ListPrompt

Kevin Zhuang edited this page Oct 5, 2021 · 14 revisions

This page is deprecated, documentation moved to: https://inquirerpy.readthedocs.io/

A basic list prompt which let user select choice(s).

class ListPrompt(BaseListPrompt):
    def __init__(
        self,
        message: Union[str, Callable[[SessionResult], str]],
        choices: Union[Callable[[SessionResult], List[Any]], List[Any]],
        default: Any = None,
        style: InquirerPyStyle = None,
        vi_mode: bool = False,
        qmark: str = "?",
        pointer: str = INQUIRERPY_POINTER_SEQUENCE,
        instruction: str = "",
        transformer: Callable[[Any], Any] = None,
        filter: Callable[[Any], Any] = None,
        height: Union[int, str] = None,
        max_height: Union[int, str] = None,
        multiselect: bool = False,
        marker: str = INQUIRERPY_POINTER_SEQUENCE,
        validate: Union[Callable[[Any], bool], Validator] = None,
        invalid_message: str = "Invalid input",
        keybindings: Dict[str, List[Dict[str, Any]]] = None,
        show_cursor: bool = True,
    ) -> None:

Example

demo

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

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

result = prompt(questions=questions)
Alternate Syntax
from InquirerPy import inquirer
from InquirerPy.separator import Separator

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

Parameters

message: Union[Callable[[SessionResult], str], str]

REQUIRED

The question message to display/ask the user.

When providing as a function, the current prompt session result will be provided as a parameter. If you are using the alternate syntax (i.e. inquirer), put a dummy parameter (_) in your function.

from InquirerPy import inquirer

def get_message(_) -> str:
    message = "Name:"
    # logic ...
    return message

result = inquirer.list(message=get_message, choices=[1, 2, 3]).execute()

choices: Union[List[Any], Callable[[SessionResult], List[Any]]]

REQUIRED

A list of choices for user to select.

When providing as a function, the current prompt session result will be provided as a parameter. If you are using the alternate syntax (i.e. inquirer), put a dummy parameter (_) in your function.

choice: Union[Any, Dict[Any, Any]]

Each choice can be either any value that have a string representation (e.g. can str(value)), or it can be a dictionary which consists of the following keys.

  • name: (Any) The display name of the choice, user will be able to see this value.
  • value: (Any) The value of the choice, can be different than the name, user will not be able to see this value.

Choice can also be a Separator instance, which can yields visual effect of separating groups of choices. Visit the documentation on Separator for more details.

default: Any

The default value of the prompt. This will be used to determine where the current highlighted choice is. It can be either a value or a callable.

When providing as a function, the current prompt session result will be provided as a parameter. If you are using the alternate syntax (i.e. inquirer), put a dummy parameter (_) in your function.

The default value should be either one of the choices or it should be one of the choices["value"] if choice are a dictionary.

style: InquirerPy

If you are suing classic syntax (i.e. style), there's no need to provide this value since prompt already sets the style, unless you would like to apply different style for different question.

An InquirerPyStyle instance. Use get_style to retrieve an instance, reference Style documentation for more information.

vi_mode: bool

If you are suing classic syntax (i.e. prompt), there's no need to provide this value since prompt already sets sets this value, unless you would like to apply vi_mode to specific questions.

Enable vim keybindings for the list prompt. It will change the up navigation from ctrl-p/up to k/up and down navigation from ctrl-n/down to j/down. Checkout Keybindings documentation for more information.

qmark: str

The question mark symbol to display in front of the question. By default, the qmark is ?.

? Question1
? Question2

pointer: str

The pointer symbol which indicates the current selected choice. Reference Style for detailed information on prompt components.

The default symbol is a unicode char .

? Question: █
  choice1
❯ choice2
  choice3

instruction: str

Optionally provide some instruction to the user such as navigation keybindings or how many choices they should select. This will be displayed right after the question message in the prompt.

transformer: Callable[[Any], Any]

Note: filter function won't affect the answer passed into transformer, filter will manipulate the choice["value"] while the transformer function will manipulate the choice["name"].

A callable to transform the result. This is visual effect only, meaning it doesn't affect the returned result, it only changes the result displayed in the prompt.

The value provided to the transformer is name of a choice (choice["name"]) or a list of name of the choices. This means that the value may be string even if the choices only consists of other types. Reference the following example.

result = inquirer.select(
    message="Select one:", choices=[1, 2, 3], default=2
).execute()  # UI -> ? Select one: 2
result = inquirer.select(
    message="Select one:",
    choices=[1, 2, 3],
    default=2,
    transformer=lambda result: int(result) * 2,
).execute()  # UI -> ? Select one: 4

filter: Callable[[Any], Any]

A callable to filter the result. Different than the transformer, this affects the actual returned result but doesn't affect the visible prompt content.

The value provided to the filter is the value of a choice (choice["value"]) or a list of value of the choices.

result = inquirer.select(
    message="Select one:", choices=[1, 2, 3], default=2
).execute()  # result = 2
result = inquirer.select(
    message="Select one:",
    choices=[1, 2, 3],
    default=2,
    filter=lambda result: result * 2,
).execute()  # result = 4

height: Union[int, str]

Note: for a better experience, setting the max_height is the preferred way of specifying the height. max_height allow the height of the prompt to be more dynamic, prompt will only take as much space as it needs. When reaching max_height, user will be able to scroll.

Set the height of the list prompt. This parameter can be used to control how much height the prompt should take. The height parameter will set the prompt height to a fixed value no matter how much space the content requires.

When content is less than the height, height will be extended to the specified height even if the content doesn't require that much space leaving areas blank.

When content is greater than the height, user will be able to scroll through the prompt when navigating up/down.

The value of height can be either a int or a string. An int indicates an exact value in how many lines in the terminal the prompt should take. (e.g. setting height to 1 will cause the prompt to only display 1 choice at a time). A str indicates a percentile in respect to the entire visible terminal.

The following example will only display 2 choices at a time, meaning only the choice 1 and 2 will be visible. The choice 3 will be visible when user scroll down.

result = inquirer.list(
    message="Select one:",
    choices=[1, 2, 3],
    default=2,
    height=2
).execute()

The following example will cause the list prompt to take 50% of the entire terminal.

result = inquirer.list(
    message="Select one:",
    choices=[1, 2, 3],
    default=2,
    height="50%" # or just "50"
).execute()

max_height: Union[int, str]

The default max_height for all prompt is "60%" if both height and max_height is not provided.

This value controls the maximum height the prompt can grow. When reaching the maximum height, user will be able to scroll.

The value of max_height can be either a int or a string. An int indicates an exact value in how many lines in the terminal the prompt can take. (e.g. setting height to 1 will cause the prompt to only display 1 choice at a time). A str indicates a percentile in respect to the entire visible terminal.

The following example will let the list prompt to display all of its content unless the visible terminal is less 10 lines in which 9 * 0.5 - 2 is not enough to display all 3 choices, then user will be able to scroll.

result = inquirer.list(
    message="Select one:",
    choices=[1, 2, 3],
    default=2,
    max_height="50%" # or just "50"
).execute()

multiselect: bool

Enable multiple selection of the list prompt. This enables the keybindings such as tab and shift-tab to select more choices. Visit Keybindings for detailed information on keybindings.

Setting this value to True also change the result from a single value to a list of values.

marker: str

A symbol indicating the selected/marked choices. When a choice is selected using keybindings such as tab or space, this symbol will be displayed between the pointer and choice. Reference Style for more details on prompt components.

The default symbol is an unicode .

? Question: █
 ❯choice1
❯❯choice2
  choice3

validate: Union[Callable[[str], bool], Validator]

Provide the validator for this question. Checkout Validator documentation for full details.

An effective way of using validator against a list prompt would be checking and enforcing the minimum choices thats required to be selected in a multiselect scenario.

invalid_message: str

Configure the error message to display to the user when input does not meet compliance.

If the validate parameter is a Validator instance, then skip this parameter.

keybindings: Dict[str, List[Dict[str, Any]]]

Provide a dictionary of custom keybindings to apply to this prompt. For more information of keybindings, reference Keybindings section.

show_cursor: bool

By default, InquirerPy will display cursor at the end of the list prompt. Set to False if you prefer to hide the cursor.

Clone this wiki locally