Into my function I'm expecting an argument that may either be a tuple
or a str
. Being new to Python, I have learned that 'begging forgiveness' is better than 'asking for permission'. So instead of checking the type of the argument, I'm doing this:
def f(a):
try: # to handle as tuple
e1, e2, e3 = a
...
except ValueError: # unpacking failed, so must be a string.
pass
# handle as string
However, this won't always work. What if a
is a str
of length 3
? The code would treat it as a tuple.
What should I do in this case? Resort to type checking? Is it less 'Pythonic'? Please explain the most 'Pythonic' solution and why it is so.