← pod_r2_v1e

rich_3052

failed WRONG_FIX wrong_fix · 8 tool calls · 224 s · Textualize/rich

Task input

Case insensitive prompt choices

## Type of changes

- [ ] Bug fix
- [x] New feature
- [ ] Documentation / docstrings
- [ ] Tests
- [ ] Other

## Checklist

- [x] I've run the latest [black](https://github.com/psf/black) with default args on new code.
- [x] I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate.
- [x] I've added tests for new code.
- [x] I accept that @willmcgugan may be pedantic in the code review.

## Description

Optional flag for `Prompt.ask` allowing case-insensitive responses. Just add `case_sensitive=False` to the command options:

```python
from rich.prompt import Prompt
name = Prompt.ask("Enter your name", choices=["Paul", "Jessica", "Duncan"], default="Paul", case_sensitive=False)
```

Now, it would accept "paul" or "Paul" as valid responses. Defaults to True, which is the usual result.


Tool calls (9)

#ToolArgumentsResult
1run_command
{
 "command": "grep -rn \"class Prompt\" rich | head -20"
}
{"status": "ok", "stdout": "rich/prompt.py:11:class PromptError(Exception):\nrich/prompt.py:30:class PromptBase(Generic[PromptType]):\nrich/prompt.py:286:class
full
{"status": "ok", "stdout": "rich/prompt.py:11:class PromptError(Exception):\nrich/prompt.py:30:class PromptBase(Generic[PromptType]):\nrich/prompt.py:286:class Prompt(PromptBase[str]):\n", "stderr": "", "exit_code": 0}
2run_command
{
 "command": "sed -n '286,350p' rich/prompt.py"
}
{"status": "ok", "stdout": "class Prompt(PromptBase[str]):\n \"\"\"A prompt that returns a str.\n\n Example:\n >>> name = Prompt.ask(\"Enter your name\")\n\n\n
full
{"status": "ok", "stdout": "class Prompt(PromptBase[str]):\n    \"\"\"A prompt that returns a str.\n\n    Example:\n        >>> name = Prompt.ask(\"Enter your name\")\n\n\n    \"\"\"\n\n    response_type = str\n\n\nclass IntPrompt(PromptBase[int]):\n    \"\"\"A prompt that returns an integer.\n\n    Example:\n        >>> burrito_count = IntPrompt.ask(\"How many burritos do you want to order\")\n\n    \"\"\"\n\n    response_type = int\n    validate_error_message = \"[prompt.invalid]Please enter a valid integer number\"\n\n\nclass FloatPrompt(PromptBase[int]):\n    \"\"\"A prompt that returns a float.\n\n    Example:\n        >>> temperature = FloatPrompt.ask(\"Enter desired temperature\")\n\n    \"\"\"\n\n    response_type = float\n    validate_error_message = \"[prompt.invalid]Please enter a number\"\n\n\nclass Confirm(PromptBase[bool]):\n    \"\"\"A yes / no confirmation prompt.\n\n    Example:\n        >>> if Confirm.ask(\"Continue\"):\n                run_job()\n\n    \"\"\"\n\n    response_type = bool\n    validate_error_message = \"[prompt.invalid]Please enter Y or N\"\n    choices: List[str] = [\"y\", \"n\"]\n\n    def render_default(self, default: DefaultType) -> Text:\n        \"\"\"Render the default as (y) or (n) rather than True/False.\"\"\"\n        yes, no = self.choices\n        return Text(f\"({yes})\" if default else f\"({no})\", style=\"prompt.default\")\n\n    def process_response(self, value: str) -> bool:\n        \"\"\"Convert choices to a bool.\"\"\"\n        value = value.strip().lower()\n        if value not in self.choices:\n            raise InvalidResponse(self.validate_error_message)\n        return value == self.choices[0]\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    from rich import print\n", "stderr": "", "exit_code": 0}
3run_command
{
 "command": "sed -n '30,150p' rich/prompt.py"
}
{"status": "ok", "stdout": "class PromptBase(Generic[PromptType]):\n \"\"\"Ask the user for input until a valid response is received. This is the base class, se
full
{"status": "ok", "stdout": "class PromptBase(Generic[PromptType]):\n    \"\"\"Ask the user for input until a valid response is received. This is the base class, see one of\n    the concrete classes for examples.\n\n    Args:\n        prompt (TextType, optional): Prompt text. Defaults to \"\".\n        console (Console, optional): A Console instance or None to use global console. Defaults to None.\n        password (bool, optional): Enable password input. Defaults to False.\n        choices (List[str], optional): A list of valid choices. Defaults to None.\n        show_default (bool, optional): Show default in prompt. Defaults to True.\n        show_choices (bool, optional): Show choices in prompt. Defaults to True.\n    \"\"\"\n\n    response_type: type = str\n\n    validate_error_message = \"[prompt.invalid]Please enter a valid value\"\n    illegal_choice_message = (\n        \"[prompt.invalid.choice]Please select one of the available options\"\n    )\n    prompt_suffix = \": \"\n\n    choices: Optional[List[str]] = None\n\n    def __init__(\n        self,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n        show_choices: bool = True,\n    ) -> None:\n        self.console = console or get_console()\n        self.prompt = (\n            Text.from_markup(prompt, style=\"prompt\")\n            if isinstance(prompt, str)\n            else prompt\n        )\n        self.password = password\n        if choices is not None:\n            self.choices = choices\n        self.show_default = show_default\n        self.show_choices = show_choices\n\n    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n       
4run_command
{
 "command": "sed -n '151,250p' rich/prompt.py"
}
{"status": "ok", "stdout": " \"\"\"\n return Text(f\"({default})\", \"prompt.default\")\n\n def make_prompt(self, default: DefaultType) -> Text:\n \"\"\"Make pr
full
{"status": "ok", "stdout": "        \"\"\"\n        return Text(f\"({default})\", \"prompt.default\")\n\n    def make_prompt(self, default: DefaultType) -> Text:\n        \"\"\"Make prompt text.\n\n        Args:\n            default (DefaultType): Default value.\n\n        Returns:\n            Text: Text to display in prompt.\n        \"\"\"\n        prompt = self.prompt.copy()\n        prompt.end = \"\"\n\n        if self.show_choices and self.choices:\n            _choices = \"/\".join(self.choices)\n            choices = f\"[{_choices}]\"\n            prompt.append(\" \")\n            prompt.append(choices, \"prompt.choices\")\n\n        if (\n            default != ...\n            and self.show_default\n            and isinstance(default, (str, self.response_type))\n        ):\n            prompt.append(\" \")\n            _default = self.render_default(default)\n            prompt.append(_default)\n\n        prompt.append(self.prompt_suffix)\n\n        return prompt\n\n    @classmethod\n    def get_input(\n        cls,\n        console: Console,\n        prompt: TextType,\n        password: bool,\n        stream: Optional[TextIO] = None,\n    ) -> str:\n        \"\"\"Get input from user.\n\n        Args:\n            console (Console): Console instance.\n            prompt (TextType): Prompt text.\n            password (bool): Enable password entry.\n\n        Returns:\n            str: String from user.\n        \"\"\"\n        return console.input(prompt, password=password, stream=stream)\n\n    def check_choice(self, value: str) -> bool:\n        \"\"\"Check value is in the list of valid choices.\n\n        Args:\n            value (str): Value entered by user.\n\n        Returns:\n            bool: True if choice was valid, otherwise False.\n        \"\"\"\n        assert self.choices is not None\n        return value.strip() in self.choices\n\n    def process_response(self, value: str) -> PromptType:\n        \"\"\"Process response from user, convert to 
5run_command
{
 "command": "python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"rich/prompt.py\"); s = p.read_text()\n\n# Update PromptBase docstring\nold_doc = \"\"\"        choices (List[str], optional): A list of valid choices. Defaults to None.\n        show_default (bool, optional): Show default in prompt. Defaults to True.\n        show_choices (bool, optional): Show choices in prompt. Defaults to True.\"\"\"\nnew_doc = \"\"\"        choices (List[str], optional): A list of valid choices. Defaults to None.\n        case_sensitive (bool, optional): Whether choices are case-sensitive. Defaults to True.\n        show_default (bool, optional): Show default in prompt. Defaults to True.\n        show_choices (bool, optional): Show choices in prompt. Defaults to True.\"\"\"\ns = s.replace(old_doc, new_doc)\n\n# Update PromptBase.__init__\nold_init = \"\"\"    def __init__(\n        self,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n        show_choices: bool = True,\n    ) -> None:\n        self.console = console or get_console()\n        self.prompt = (\n            Text.from_markup(prompt, style=\"prompt\")\n            if isinstance(prompt, str)\n            else prompt\n        )\n        self.password = password\n        if choices is not None:\n            self.choices = choices\n        self.show_default = show_default\n        self.show_choices = show_choices\"\"\"\nnew_init = \"\"\"    def __init__(\n        self,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        case_sensitive: bool = True,\n        show_default: bool = True,\n        show_choices: bool = True,\n    ) -> None:\n        self.console = console or get_console()\n        self.prompt = (\n            Text.from_markup(prompt, style=\"prompt\")\n            if isinstance(prompt, str)\n            else prompt\n        )\n        self.password = password\n        if choices is not None:\n            self.choices = choices\n        self.case_sensitive = case_sensitive\n        self.show_default = show_default\n        self.show_choices = show_choices\"\"\"\ns = s.replace(old_init, new_init)\n\n# Update PromptBase.ask overloads\n# Overload 1\nold_overload1 = \"\"\"    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n        show_choices: bool = True,\n        default: DefaultType,\n        stream: Optional[TextIO] = None,\n    ) -> Union[DefaultType, PromptType]:\"\"\"\nnew_overload1 = \"\"\"    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        case_sensitive: bool = True,\n        show_default: bool = True,\n        show_choices: bool = True,\n        default: DefaultType,\n        stream: Optional[TextIO] = None,\n    ) -> Union[DefaultType, PromptType]:\"\"\"\ns = s.replace(old_overload1, new_overload1)\n\n# Overload 2\nold_overload2 = \"\"\"    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n        show_choices: bool = True,\n        stream: Optional[TextIO] = None,\n    ) -> PromptType:\"\"\"\nnew_overload2 = \"\"\"    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bo
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
6run_command
{
 "command": "python3 - <<'PY'\nfrom rich.prompt import Prompt\nfrom unittest.mock import MagicMock\n\ndef test_case_insensitive_prompt():\n    console = MagicMock()\n    # Mock console.input to return \"paul\"\n    console.input.return_value = \"paul\"\n    \n    # This should work if case_sensitive=False\n    # We use a mock console to avoid actual input()\n    # Prompt.ask returns the result of _prompt(default=default, stream=stream)\n    # _prompt is an instance of Prompt.\n    # The __call__ method of PromptBase handles the loop.\n    \n    # Since we can't easily mock the loop without more effort, \n    # let's just test check_choice directly.\n    \n    prompt = Prompt(\"Enter name\", choices=[\"Paul\", \"Jessica\", \"Duncan\"], case_sensitive=False)\n    assert prompt.check_choice(\"paul\") is True\n    assert prompt.check_choice(\"PAUL\") is True\n    assert prompt.check_choice(\"Paul\") is True\n    assert prompt.check_choice(\"Other\") is False\n    \n    prompt_sensitive = Prompt(\"Enter name\", choices=[\"Paul\", \"Jessica\", \"Duncan\"], case_sensitive=True)\n    assert prompt_sensitive.check_choice(\"paul\") is False\n    assert prompt_sensitive.check_choice(\"Paul\") is True\n\nprint(\"Tests passed!\")\nPY\n"
}
{"status": "ok", "stdout": "Tests passed!\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "Tests passed!\n", "stderr": "", "exit_code": 0}
7run_command
{
 "command": "git diff rich/prompt.py"
}
{"status": "ok", "stdout": "diff --git a/rich/prompt.py b/rich/prompt.py\nindex 064c959b..771dc297 100644\n--- a/rich/prompt.py\n+++ b/rich/prompt.py\n@@ -36,6
full
{"status": "ok", "stdout": "diff --git a/rich/prompt.py b/rich/prompt.py\nindex 064c959b..771dc297 100644\n--- a/rich/prompt.py\n+++ b/rich/prompt.py\n@@ -36,6 +36,7 @@ class PromptBase(Generic[PromptType]):\n         console (Console, optional): A Console instance or None to use global console. Defaults to None.\n         password (bool, optional): Enable password input. Defaults to False.\n         choices (List[str], optional): A list of valid choices. Defaults to None.\n+        case_sensitive (bool, optional): Whether choices are case-sensitive. Defaults to True.\n         show_default (bool, optional): Show default in prompt. Defaults to True.\n         show_choices (bool, optional): Show choices in prompt. Defaults to True.\n     \"\"\"\n@@ -57,6 +58,7 @@ class PromptBase(Generic[PromptType]):\n         console: Optional[Console] = None,\n         password: bool = False,\n         choices: Optional[List[str]] = None,\n+        case_sensitive: bool = True,\n         show_default: bool = True,\n         show_choices: bool = True,\n     ) -> None:\n@@ -69,6 +71,7 @@ class PromptBase(Generic[PromptType]):\n         self.password = password\n         if choices is not None:\n             self.choices = choices\n+        self.case_sensitive = case_sensitive\n         self.show_default = show_default\n         self.show_choices = show_choices\n \n@@ -81,6 +84,7 @@ class PromptBase(Generic[PromptType]):\n         console: Optional[Console] = None,\n         password: bool = False,\n         choices: Optional[List[str]] = None,\n+        case_sensitive: bool = True,\n         show_default: bool = True,\n         show_choices: bool = True,\n         default: DefaultType,\n@@ -97,6 +101,7 @@ class PromptBase(Generic[PromptType]):\n         console: Optional[Console] = None,\n         password: bool = False,\n         choices: Optional[List[str]] = None,\n+        case_sensitive: bool = True,\n         show_default: bool = True,\n         show_choices: bool = True,\n    
8run_command
{
 "command": "submit_patch"
}
{"status": "error", "error_type": "CommandError", "error_message": "/bin/bash: submit_patch: command not found\n", "details": {"stdout": "", "stderr": "/bin/bas
full
{"status": "error", "error_type": "CommandError", "error_message": "/bin/bash: submit_patch: command not found\n", "details": {"stdout": "", "stderr": "/bin/bash: submit_patch: command not found\n", "exit_code": 127}}
9submit_patch
{}
{"status": "ok", "patch_size": 3687, "files_changed": 1}
full
{"status": "ok", "patch_size": 3687, "files_changed": 1}

Patch

diff --git a/rich/prompt.py b/rich/prompt.py
index 064c959b..771dc297 100644
--- a/rich/prompt.py
+++ b/rich/prompt.py
@@ -36,6 +36,7 @@ class PromptBase(Generic[PromptType]):
         console (Console, optional): A Console instance or None to use global console. Defaults to None.
         password (bool, optional): Enable password input. Defaults to False.
         choices (List[str], optional): A list of valid choices. Defaults to None.
+        case_sensitive (bool, optional): Whether choices are case-sensitive. Defaults to True.
         show_default (bool, optional): Show default in prompt. Defaults to True.
         show_choices (bool, optional): Show choices in prompt. Defaults to True.
     """
@@ -57,6 +58,7 @@ class PromptBase(Generic[PromptType]):
         console: Optional[Console] = None,
         password: bool = False,
         choices: Optional[List[str]] = None,
+        case_sensitive: bool = True,
         show_default: bool = True,
         show_choices: bool = True,
     ) -> None:
@@ -69,6 +71,7 @@ class PromptBase(Generic[PromptType]):
         self.password = password
         if choices is not None:
             self.choices = choices
+        self.case_sensitive = case_sensitive
         self.show_default = show_default
         self.show_choices = show_choices
 
@@ -81,6 +84,7 @@ class PromptBase(Generic[PromptType]):
         console: Optional[Console] = None,
         password: bool = False,
         choices: Optional[List[str]] = None,
+        case_sensitive: bool = True,
         show_default: bool = True,
         show_choices: bool = True,
         default: DefaultType,
@@ -97,6 +101,7 @@ class PromptBase(Generic[PromptType]):
         console: Optional[Console] = None,
         password: bool = False,
         choices: Optional[List[str]] = None,
+        case_sensitive: bool = True,
         show_default: bool = True,
         show_choices: bool = True,
         stream: Optional[TextIO] = None,
@@ -111,6 +116,7 @@ class PromptBase(Generic[PromptType]):
         console: Optional[Console] = None,
         password: bool = False,
         choices: Optional[List[str]] = None,
+        case_sensitive: bool = True,
         show_default: bool = True,
         show_choices: bool = True,
         default: Any = ...,
@@ -126,6 +132,7 @@ class PromptBase(Generic[PromptType]):
             console (Console, optional): A Console instance or None to use global console. Defaults to None.
             password (bool, optional): Enable password input. Defaults to False.
             choices (List[str], optional): A list of valid choices. Defaults to None.
+            case_sensitive (bool, optional): Whether choices are case-sensitive. Defaults to True.
             show_default (bool, optional): Show default in prompt. Defaults to True.
             show_choices (bool, optional): Show choices in prompt. Defaults to True.
             stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None.
@@ -135,6 +142,7 @@ class PromptBase(Generic[PromptType]):
             console=console,
             password=password,
             choices=choices,
+            case_sensitive=case_sensitive,
             show_default=show_default,
             show_choices=show_choices,
         )
@@ -212,6 +220,8 @@ class PromptBase(Generic[PromptType]):
             bool: True if choice was valid, otherwise False.
         """
         assert self.choices is not None
+        if not self.case_sensitive:
+            return value.strip().lower() in [c.lower() for c in self.choices]
         return value.strip() in self.choices
 
     def process_response(self, value: str) -> PromptType:

Test output

show
.F
=================================== FAILURES ===================================
_______________________ test_prompt_str_case_insensitive _______________________

    def test_prompt_str_case_insensitive():
        INPUT = "egg\nFoO"
        console = Console(file=io.StringIO())
        name = Prompt.ask(
            "what is your name",
            console=console,
            choices=["foo", "bar"],
            default="baz",
            case_sensitive=False,
            stream=io.StringIO(INPUT),
        )
>       assert name == "foo"
E       AssertionError: assert 'FoO' == 'foo'
E         
E         - foo
E         + FoO

tests/test_prompt.py:35: AssertionError
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
1 failed, 1 passed in 0.10s