Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

multiple variable return - nargout in Python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...