I realize that there have already been discussions on whether to use If/Else or Try/Except blocks. Such a question is located here: Better to 'try' something and catch the exception or test if its possible first to avoid an exception?
But I'd like to expand the discussion a little further to nested try/except
and nested if/elif/else
logic blocks. Here's the set up... I want to write a function that will allow users to provide either a string literal, an integer, or an iterable. This is a high level function that will provide some level of abstraction to other functions I have written. My code is like so:
def high_level_func(parameter = None):
"""
:param parameter: Can accept the string 'All', a single integer, or an iterable such
as a range or a list or tuple of ints.
"""
try:
if parameter.lower() == 'all'
# .lower because str input should be case-insensitive
return str_all_function(parameter) # Only accepts the
# string 'all' - case insensitive
except AttributeError:
# if parameter is an int or iter end up here because those types
# don't have .lower() methods
try:
for para in parameter:
try:
print(int_input_function(parameter))
except MyException:
raise MyException('An iter of something other than ints was '
'provided and cause this error.')
except TypeError:
# parameter must be an int because ints aren't iterable and end up here
return int_input_function(parameter)
In this case let's assume that I have no idea what type of input most users will prefer (i.e. it is equally likely that any given user will pass either an int
, an iter
, or the string 'all'. But we can safely assume that the user will most likely never pass a list of strings or tuple of strings -illegal iter
s)
Is this ok to do or would I be better off checking the type of the input and doing an if/elif/else (IEE) code block? Would an IEE code block be significantly easier to read in your opinion?
Alternative suggestion: what about using a combination of try/except and IEE? The try/except might try to lower the input if it is the string literal 'all', for example, and the IEE would be nested in the except
block to check the alternative cases (integer or iter or illegal type)
And in more general, how can I tell which method is the fastest without writing the function three different times and testing each one?
An even further question is, if the Try/Except is faster on average than an If/Elif/Else test, but we think If/Elif/Else has better readability, how much faster should the Try/Except method be to warrant throwing readability out the window or does readability always prevail in the face of speed? Or is this up to the coder's/team's discretion?