Reputation: 1718
I have a tuple x = (2,)
to which I would like to append a variable y
. I do not know ahead of time exactly what kind of variable y
will be.
y
could be:
x+y
, orx+(y,)
.Adopting one strategy will give me a TypeError half of the time, and adopting the other will give me (2, (3, 4))
when I want (2, 3, 4)
.
What's the best way to handle this?
Upvotes: 6
Views: 2528
Reputation: 9561
Use the second strategy, just check whether you're adding an iterable with multiple items or a single item.
You can see if an object is an iterable (tuple
, list
, etc.) by checking for the presence of an __iter__
attribute. For example:
# Checks whether the object is iterable, like a tuple or list, but not a string.
if hasattr(y, "__iter__"):
x += tuple(y)
# Otherwise, it must be a "single object" as you describe it.
else:
x += (y,)
Try this. This snippet will behave exactly like you describe in your question.
Note that in Python 3, strings have an __iter__
method. In Python 2.7:
>>> hasattr("abc", "__iter__")
False
In Python 3+:
>>> hasattr("abc","__iter__")
True
If you are on Python 3, which you didn't mention in your question, replace hasattr(y, "__iter__")
with hasattr(y, "__iter__") and not isinstance(y, str)
. This will still account for either tuples or lists.
Upvotes: 4
Reputation: 52071
Use isinstance
in a if
condition.
>>> x = (2,)
>>> y1 = (1,2)
>>> y2 = 2
>>> def concat_tups(x,y):
... return x + (y if isinstance(y,tuple) else (y,))
...
>>> concat_tups(x,y2)
(2, 2)
>>> concat_tups(x,y1)
(2, 1, 2)
>>>
Upvotes: 1