nargout in Python

Nik picture Nik · Jan 3, 2013 · Viewed 15.9k times · Source

Does Python have any equivalent of nargout in MATLAB? I find nargout a very neat approach if we want to keep the number of return parameters flexible. Is there a way I can find out how many output parameters have been requested? Something like the following pseudo-python-code:

def var_returns_func(a):
  """
  a is a 1D numpy array
  """
  if nargout==1: return a.sum()
  elif nargout==2: return a.sum(),a.std()

So if I call this function as mean = var_returns_func(someNumPyarray), it should return a single value. But if I call it as mean,std = var_returns_func(someNumPyarray), it should return 2 values.

Is there a Pythonic way of doing this? Or a hacky way?

Answer

BrenBarn picture BrenBarn · Jan 3, 2013

The function can't know what is going to be done with the return value, so it can't know how many are needed. What you could do is pass nargout as an argument to your function and use that to decide what to return:

def f(a, nargout=1):
    if nargout == 1:
        return "one value"
    elif nargout == 2:
        return "two", "values"
    else:
        raise ValueError, "Invalid nargout!"

This is an example of "explicit is better than implicit" as a Python philosophy. If you want two arguments out, you have to say explicitly that you want two arguments out. Implicitly deciding based on looking into the future to see what is going to be done with the result is discouraged in Python. It's perfectly possible to do a = f(x) and want to get a two-element tuple in a.

For examples like yours, there are lots of better ways. One is to just do mean, std = a.mean(), a.std(), or more generally x, y = someFunc(a), otherFunc(a). If this particular combination of values is commonly needed, and there is some expensive computation shared by both operations that you don't want to duplicate, make a third function that clearly returns both and do x, y = funcThatReturnsTwoThings(a). All of these are explicit ways of keeping functions separate if they do different things.