enforce arguments to a specific list of values

You need to check the value inside the function:

def results(status, data):
    valid = {0, 1, 99}
    if status not in valid:
        raise ValueError("results: status must be one of %r." % valid)

Here, valid is a set, because the only thing we care about is whether status is a member of the collection (we aren’t interested in order, for example). To avoid recreating the set each time you use the function, you’d probably define it as a “constant”1 global:

VALID_STATUS = {0, 1, 99}

def results(status, data):
    if status not in VALID_STATUS:
        raise ValueError("results: status must be one of %r." % VALID_STATUS)

Example usage:

>>> results(7, [...])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in results
ValueError: results: status must be one of {0, 1, 99}.

Always try to raise the most appropriate exception you can – ValueError tells the caller of the function what’s going on better than Exception does, for example.


1 It’s not really constant, but by convention, ALL_UPPERCASE variable names in Python are considered to be intended as constants.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)