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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…