Python processing IF block with two possible values

If I have a function or method that takes a parameter that can be only one of two values, is it more pythonic to explicitly specify both known conditions and abstract ones in the else clause? For instance:

Option 1:

def main(group_name):
    if group_name == 'request':
        do_something()
    else:
        do_something_else()

Or option 2:

def main(group_name):
    if group_name == 'request':
        do_something()
    elif group_name == 'response':
        do_something_else()
    else:
        raise Exception
+4
source share
3 answers

Explicit is better than implicit. https://www.python.org/dev/peps/pep-0020/

More importantly, the second option is probably safer in many scenarios. If only two values ​​of X and Y are possible, then you should not believe that it is Y, if it is not X, and suppose with the else statement.

+7
source

Option 2, endpoints / conditions. , / , . conditions exceptions, , , .

+2

Explicit is better than implicit for PEP 20 .

eg:

def myfunct(param):
    possible_values = [x,y]

    if param not in possible_values:
         raise ValueError

    elif param == x:
         do something

    elif param == y:
         do something else
+1
source

Source: https://habr.com/ru/post/1692667/


All Articles