Question

I realise that in the below functions f returns a tuple, and g returns a list.

def f():
    return 1,2
def g():
    return [1,2]
a,b=f()
c,d=g()

I have written a function which can handle any number of arguments.

def fun(*args):
    return args

These arguments are entered like the f function above because they are the return value from a previous function.

output = fun(other_func())

When more that one value is return from fun the individual values can be retrieved by stating something like this...

output1, output2 =  fun(other_func())

However, when one argument is used the output is something like below...

output = fun(other_func())

(1,)

Is there a way when there is only one value to have it return a single element instead of a tuple but still have the functionality of being able to return more than one value?

Was it helpful?

Solution

If you know the function is always going to return a one-element tuple, you can use a one-element tuple assignment:

output, = fun(other_func())

or simply index:

output = fun(other_func())[0]

But in this case, a simple Don't do that, don't return a tuple might also apply:

output = other_func()

OTHER TIPS

As long as *args is a tuple, returning args will therefore return a tuple, even if there is only one parameter.

You should probably do something like:

def fun(*args):
    if len(args) == 1:
        args, = args
    return args

This might be what you are looking for. With this method you must have at least one argument, but you will catch the other arguments in other if you have more.

def funct(*args):
    return args
# end funct

if __name__ == '__main__':
    foo, *other = funct(1, 2, 3, 4)
    print(foo)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top