Skip to content

CheckboxPrompt

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

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

A list prompt with checkbox display.

How does it different from other list prompts with multiselect? With other list prompts that enables multiselect, the minimum choice selection will always be 1 (when user doesn't select anything, the current highlighted choice will be selected). With checkbox prompt, the current highlighted choice will not be automatically selected.

class CheckboxPrompt(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,
        enabled_symbol: str = INQUIRERPY_FILL_HEX_SEQUENCE,
        disabled_symbol: str = INQUIRERPY_EMPTY_HEX_SEQUENCE,
        instruction: str = "",
        transformer: Callable[[Any], Any] = None,
        filter: Callable[[Any], Any] = None,
        height: Union[int, str] = None,
        max_height: Union[int, str] = None,
        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

def question1_choice(_):
    return [
        {"name": "Sydney", "value": "ap-southeast-2", "enabled": True},
        {"name": "Singapore", "value": "ap-southeast-1", "enabled": False},
        Separator(),
        "us-east-1",
        "us-west-1",
    ]

def question2_choice(_):
    return [
        {"enabled": False, "name": "Apple", "value": "Apple"},
        {"enabled": False, "name": "Cherry", "value": "Cherry"},
        {"enabled": False, "name": "Orange", "value": "Orange"},
        {"enabled": False, "name": "Peach", "value": "Peach"},
        {"enabled": False, "name": "Melon", "value": "Melon"},
        {"enabled": False, "name": "Strawberry", "value": "Strawberry"},
        {"enabled": False, "name": "Grapes", "value": "Grapes"},
    ]

questions = [
    {
        "type": "checkbox",
        "message": "Select regions:",
        "choices": question1_choice,
        "transformer": lambda result: "%s region%s selected"
        % (len(result), "s" if len(result) > 1 else ""),
    },
    {
        "type": "checkbox",
        "message": "Pick your favourites:",
        "choices": question2_choice,
        "validate": lambda result: len(result) >= 1,
        "invalid_message": "should be at least 1 selection",
        "instruction": "(select at least 1)",
    },
]

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

def question1_choice(_):
    return [
        {"name": "Sydney", "value": "ap-southeast-2", "enabled": True},
        {"name": "Singapore", "value": "ap-southeast-1", "enabled": False},
        Separator(),
        "us-east-1",
        "us-west-1",
    ]

def question2_choice(_):
    return [
        {"enabled": False, "name": "Apple", "value": "Apple"},
        {"enabled": False, "name": "Cherry", "value": "Cherry"},
        {"enabled": False, "name": "Orange", "value": "Orange"},
        {"enabled": False, "name": "Peach", "value": "Peach"},
        {"enabled": False, "name": "Melon", "value": "Melon"},
        {"enabled": False, "name": "Strawberry", "value": "Strawberry"},
        {"enabled": False, "name": "Grapes", "value": "Grapes"},
    ]

regions = inquirer.checkbox(
    message="Select regions:",
    choices=question1_choice,
    transformer=lambda result: "%s region%s selected"
    % (len(result), "s" if len(result) > 1 else ""),
).execute()
fruits = inquirer.checkbox(
    message="Pick your favourites:",
    choices=question2_choice,
    validate=lambda result: len(result) >= 1,
    invalid_message="should be at least 1 selection",
    instruction="(select at least 1)",
).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.checkbox(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.
  • enabled: (bool) This will determine if the choice is in an selected state or not.

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 for checkbox can be three types of value:

  • choice: (Any) value can also just be a choice if the choice is not in a dictionary form.
  • chocie["value"]: (Any) if providing as a dictionary, default value should match one of the choice["value"].

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 checkbox 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

In PyInquirer checkbox, this is known as pointer_sign.

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

The default symbol for checkbox is a unicode char .

? Question: █
❯ ⬢ Sydney
  ⬡ Singapore
  ⬡ USA
  ⬡ China

enabled_symbol: str

In PyInquirer checkbox, this is known as selected_sign.

This parameter controls how the checkbox should look like when they are ticked.

The default value is a unicode char .

? Question: █
❯ ⬢ Sydney
  ⬡ Singapore

disabled_symbol: str

In PyInquirer checkbox, this is known as unselected_sign.

This parameter controls how the checkbox should look like when are not ticked.

The default value is a unicode char .

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.

choices = [
    {"enabled": True, "name": "1", "value": 1},
    {"enabled": False, "name": "2", "value": 2},
]

result = inquirer.checkbox(
    message="Select one:", choices=choices
).execute()  # UI -> ? Select one: [1]
result = inquirer.checkbox(
    message="Select one:",
    choices=choices,
    transformer=lambda result: [int(i) * 2 for i in result],
).execute()  # UI -> ? Select one: [2]

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.

choices = [
    {"enabled": True, "name": "1", "value": 1},
    {"enabled": False, "name": "2", "value": 2},
]

result = inquirer.list(
    message="Select one:", choices=choices
).execute()  # result = 2
result = inquirer.list(
    message="Select one:",
    choices=choices,
    filter=lambda result: [i * 2 for i in result],
).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 checkbox 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.checkbox(
    message="Select:",
    choices=[1, 2, 3],
    height=2
).execute()

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

result = inquirer.checkbox(
    message="Select:",
    choices=[1, 2, 3],
    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 checkbox 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.checkbox(
    message="Select one:",
    choices=[1, 2, 3],
    max_height="50%" # or just "50"
).execute()

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 checkbox prompt would be checking and enforcing the minimum choices that's 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 Keybinding section.

show_cursor: bool

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