How to differentiate between a Tuple and a simple String through "Duck Typing"?
python, python-2.7
Solution
In your case I recommend you do not try..except since you want to behave differently depending on the type of variable...
It is when you DO NOT behave differently that you should use try..except.
From my comment:
You should use exceptions for when your code expects things to act in the same way always and does not. here, you want the code to behave differently depending on the variable, so you should not try..except, but rather check what it is
You can use `isinstance`.
isinstance(x, tuple)
Refer to this post for the difference between `isinstance` and `type`
All about Duck Typing and Forgiveness
Using your code, and my answer to create a solution:
def proc(arg):
if isinstance(arg, tuple):
# handle as tuple
elif isinstance(arg, str):
# handle as str
else:
# unhandled?
Problem
I'm relatively new to programming so I beg your pardon if I'm making a ridiculous mistake by referring to the following as Duck Typing. I have a procedure which receives either a string or a tuple (containing strings) as a single argument. Example: ``` def proc(arg): try: arg is a tuple handle arg a tuple except: arg is a simple string handle it so ``` Depending on whether the argument is a tuple or not, I want the function to behave differently. I do not want to type check and would like to use a `try..except` process. I thought about trying `arg[0]` but strings in Python are objects as well and in that regard they behave like tuples and return something. What can I do here? Thank you.