Search code examples
pythoninputrich

rich.Prompt to retrieve two numbers or a letter


I have a coding issue I would like to share with you.

In my python code, I need some user inputs, in particular I need him to type in either a pair of float values or a specific letter from a list to execute a command.

Something like:

Enter the required values OR Q to Exit:

I have coded everything using a while loop and the basic input followed by a series of checks on the input, but instead of my dodgy code, hard to maintain, I would like to use the rich.prompt to get a easier and nicer result.

I have seen that with rich.Prompt you can get a string (also among a choices list), an integer or a float. But I cannot see anyway how to mix these things.

Do you have any suggestion?

Thanks in advance, toto


Solution

  • Did you try reading the source? rich/prompt/prompt.py

    When there isn't very good documentation, go to the source and imitate - by looking at what I linked, I came up with this:

    from typing import Union
    from rich.prompt import PromptBase
    
    
    RESPONSE_TYPE = Union[tuple[int, int], str]
    
    
    class TwoIntsOrString(PromptBase[RESPONSE_TYPE]):
        response_type = RESPONSE_TYPE
        validate_error_message = "Please enter two integers or a string."
    
        def process_response(self, value: str) -> RESPONSE_TYPE:
            try:
                return tuple(int(x) for x in value.split()[:2])
            except ValueError:
                return value
    
    
    if __name__ == "__main__":
        prompt = TwoIntsOrString("Enter two integers or a string: ")
        response = prompt.ask()
        print(f"Response: {response!r}")