Question

I've got a class attribute which can be either a string or a list of strings. I want to convert it into a tuple such that a list converts normally, but a single string becomes a single-item tuple:

[str, str] --> (str, str)

str --> (str, )

Unfortunately tuple('sting') returns ('s', 't', 'r', 'i', 'n', 'g') which is not what I expect. Is it possible to do it without type checking?

Was it helpful?

Solution

Type checking would be a great way to achieve this. How would you otherwise decide if the input was a list or a string?.

You could make a function which tests if the input is a list or a string and returns appropriately and handles the rest as you see fit. Something along the lines of

>>> def convert_to_tuple(elem):
        if isinstance(elem, list):
            return tuple(elem)
        elif isinstance(elem, basestring):
            return (elem,)
        else:
            # Do Something
            pass


>>> convert_to_tuple('abc')
('abc',)
>>> convert_to_tuple(['abc', 'def'])
('abc', 'def')

You could only check for strings too, (Assuming Python 2.x, replace basestring with str in Py3)

>>> def convert_to_tuple(elem):
        if isinstance(elem, basestring):
            return (elem,)
        else:
            return tuple(elem)


>>> convert_to_tuple('abc')
('abc',)
>>> convert_to_tuple(('abc', 'def'))
('abc', 'def')
>>> convert_to_tuple(['abc', 'def'])
('abc', 'def')

Converting the function to a one liner is possible too.

>>> def convert_to_tuple(elem):
        return (elem,) if isinstance(elem, basestring) else tuple(elem)

OTHER TIPS

You can do this:

>>> s = 'str'
>>> print (s,)
('str',)

There's no need to call tuple() when dealing with strings to achieve what you're trying.

If you need one method to help both types, then you can't avoid type checking:

def tuplising(typ):
    return tuple(typ) if isinstance(typ, list) else (typ,)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top