Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Python functions know how many outputs are requested? [duplicate]

Tags:

python

In Python, do functions know how many outputs are requested? For instance, could I have a function that normally returns one output, but if two outputs are requested, it does an additional calculation and returns that too?

Or is this not the standard way to do it? In this case, it would be nice to avoid an extra function argument that says to provide a second input. But I'm interested in learning the standard way to do this.

like image 873
Mr. W. Avatar asked Dec 15 '22 08:12

Mr. W.


2 Answers

The real and easy answer is: No.

Python functions/methods does not know about how many outputs are requested, as unpacking of a returned tuple happens after the function call.

What's quite a best practice to do though is to use underscore (_) as a placeholder for unused args that are returned from functions when they're not needed, example:

def f():
    return 1, 2, 3

a, b, c = f()  # if you want to use all
a, _, _ = f()  # use only first element in the returned tuple, 'a'
_, b, _ = f()  # use only 'b'

For example, when using underscore (_) pylint will suppress any unused argument warnings.

like image 155
Niklas9 Avatar answered Dec 16 '22 21:12

Niklas9


Python functions always return exactly 1 value.

In this case:

def myfunc():
    return

that value is None. In this case:

def myfunc():
    return 1, 2, 3

that value is the tuple (1, 2, 3).

So there is nothing for the function to know, really.

As for returning different outputs controlled by parameters, I'm always on the fence about that. It would depend on the actual use case. For a public API that is used by others, it is probably best to provide two separate functions with different return types, that call private code that does take the parameter.

like image 29
RemcoGerlich Avatar answered Dec 16 '22 21:12

RemcoGerlich