regex doesn't seem to work in allowRegexes parameter when using pyinputplus

Viewed 105

I am using pyinputplus and specifically inputNum https://pyinputplus.readthedocs.io/en/latest/

This is what my code looks like:

msg = 'Enter value to add/replace or s to skip field or q to quit: '
answer = pyip.inputNum(prompt=msg, allowRegexes=r'^[qQsS]$', blank=False)

My goal is to allow any number but also allow one of the following q,Q,s,S.

However when I run the code and enter 'sam' the code crashes because later on I am trying to convert to float(answer).

My expectation is that allowRegexes will not allow this and will show me the prompt again to re-enter. Please advise!

1 Answers

It seems pyip.inputNum stops validating the input if you provide allowRegexes argument. See the allowRegexes doesn't seem work properly Github issue.

You can use the inputCustom method with a custom validation method:

import pyinputplus as pyip
import ast

def is_numeric(x):
    try:
        number = ast.literal_eval(x)
    except:
        return False
    return isinstance(number, float) or isinstance(number, int)

def raiseIfInvalid(text):
    if not is_numeric(text) and not text.casefold() in ['s', 'q']:
        raise Exception('Input must be numeric or "q"/"s".')

msg = 'Enter value to add/replace or s to skip field or q to quit: '
answer = pyip.inputCustom(raiseIfInvalid, prompt=msg)

So, if the text is not and int or float and not equal to s/S/q/Q, the prompt will repeat showing up.

Related