What's the best practice for handling single-value tuples in Python?

python, tuples

Solution

You need to somehow test for the type, if it's a string or a tuple. I'd do it like this:

keywords = library.get_keywords()
if not isinstance(keywords, tuple):
    keywords = (keywords,) # Note the comma
for keyword in keywords:
    do_your_thang(keyword)

Problem

I am using a 3rd party library function which reads a set of keywords from a file, and is supposed to return a tuple of values. It does this correctly as long as there are at least two keywords. However, in the case where there is only one keyword, it returns a raw string, not a tuple of size one. This is particularly pernicious because when I try to do something like ``` for keyword in library.get_keywords(): # Do something with keyword ``` , in the case of the single keyword, the `for` iterates over each character of the string in succession, which throws no exception, at run-time or otherwise, but is nevertheless completely useless to me. My question is two-fold: Clearly this is a bug in the library, which is out of my control. How can I best work around it? Secondly, in general, if I am writing a function that returns a tuple, what is the best practice for ensuring tuples with one element are correctly generated? For example, if I have ``` def tuple_maker(values): my_tuple = (values) return my_tuple for val in tuple_maker("a string"): print "Value was", val for val in tuple_maker(["str1", "str2", "str3"]): print "Value was", val ``` I get ``` Value was a Value was Value was s Value was t Value was r Value was i Value was n Value was g Value was str1 Value was str2 Value was str3 ``` What is the best way to modify the function `my_tuple` to actually return a tuple when there is only a single element? Do I explicitly need to check whether the size is 1, and create the tuple seperately, using the `(value,)` syntax? This implies that any function that has the possibility of returning a single-valued tuple must do this, which seems hacky and repetitive. Is there some elegant general solution to this problem?

Original source