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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With