I struggled to formulate the question, due to the lack of terminology on my part. I am not asking about keyword arguments with default value. My question is about how to handle argument values that can only have a set of values, and how to optimise for code readability and prevent repetitions.
See this function for example:
def foo(opt='something'):
if opt == 'something':
ret = dowhatever()
elif opt == 'somethingelse':
ret = dowhateverelse()
else:
raise UnrecognisedArgumentException(opt)
return ret
In my opinion, this is quite ugly. Its basically a not-so-good-looking java-switch translation in python. A problem that arises is when the cases have common code (repetition) in between case-associated code, which I want to avoid. If I were to avoid this I would write:
def foo(opt='something'):
if opt not in ['something', 'something_else']:
raise UnrecognisedArgumentException
if opt == 'something':
ret = do_whatever()
elif opt == 'something_else':
ret = do_whatever_else()
do_something_universal(ret)
if opt == 'something':
ret = do_whatever_afterwards()
elif opt == 'something_else':
ret = do_whatever_else_afterwards()
return ret
This is even uglier. Is there a better way of writing code like this?