Question

How do I create a simple tuple containing a variable of any time without creating a tuple of tuples? For example a function can accept either an int or a tuple of ints. Inside the function I want to make sure that the variable is in fact a tuple.

So far I could think of

a = tuple(a)

and

a = (a,)

However the first one doesnt work if a is not iterable and the second one creates a tuple of a tuple if a is already one.

((1,2),)

I feel like I should be able to do that without checking the type first... What am I missing?

Was it helpful?

Solution

You can use exception handling; try calling iter() on the object, for example

try:
    iter(a)
except TypeError:
    # not an iterable, assume a single value
    a = (a,)

If you were planning to iterate over the tuple to handle values anyway, you just store the output of the iter() call and use it directly:

try:
    a = iter(a)
except TypeError:
    a = (a,)

for elem in a:

You can also make your function signature accept multiple parameters:

def foobar(*a):
    for elem in a:

Now a is always a tuple, but to pass in a tuple you'd have to call it with:

sometuple = (1, 2, 3)
foobar(*sometuple)

while a single value is passed in as:

foobar(singlevalue)

OTHER TIPS

You can use a lambda function:

a = (lambda x: x if type(x) is tuple else (x,))(a)

Perhaps more verbose than what you wanted, but it allows you to keep it all in one line.

Unfortunately, there's really no way to do it without checking the type of the argument. When you try to construct a tuple from another tuple - e.g. t = (tup,) - it's treated as a generic Python object, i.e. it doesn't "know" that it's a tuple. In order for it to auto-expand the tuple, it will have to check it's type first.

A non-iterable object would also have to be identified, because it doesn't contain the necessary methods to iterate over it's elements. In other words, a non-iterable - e.g. a scalar - isn't just an iterable with a single element. They're completely different object types. It can be placed in a tuple, but not converted to one.

When you use the tuple function to create a tuple, it just treats the input as a generic iterable. It doesn't know that it's a tuple.

So whether the type check is done internally by tuple(), or by the calling function, it will still have to be done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top