Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic handling of IF block with two possible values

Tags:

python

If I have a function or method which accepts a parameter which can only be one of two values, is it more pythonic to explicitly state both known conditions or abstract one away in the else clause? For example:

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
like image 806
Mark Riddell Avatar asked Dec 24 '22 10:12

Mark Riddell


1 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 X and Y are possible, then you shouldn't trust that it is Y if it isn't X and assume that with the else statement.

like image 74
fabiomaia Avatar answered Dec 26 '22 00:12

fabiomaia