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 f
I cannot speak for nargout in MATLAB as I do not know it and I cannot imagine how it should be used correctly. However, you may want to change you view to what a Python function (or method) really does).
Actually, Python always returns exactly one value. Or it is None, or it is a single value of some specific type, or it is a single object of the tuple type.
If there is no return command, the function returns None if the function body ends. It is the same as if you explicitly wrote return without arguments at the end of body, or return None at the end of body.
If you use return None (the None can be stored in a variable) or return without arguments, the None is returne to the caller.
If you return single, the single object is return to the caller.
If you return v1, v2, v3, you actually return a tuple (v1, v2, v3). It is just a syntactic sugar that you need not to write the parentheses.
The result1, result2, result3 = f() in the case is just another syntactic sugar. The f() returns the tuple and its elements are automatically extracted to the given variables. You actually do:
result1, result2, result3 = (v1, v2, v3)
or
t = f() # where t is the (v1, v2, v3)
result1, result2, result3 = t
Actually, Python does not allow to define output arguments as it is usual in other languages. You can think in terms you are passing addresses of the argument objects and if the passed object allows to be modified, you can modify it. But you can never get a new result to a passed argument that had initially None value, for example. You cannot assign a Python variable via output argument of the function -- no mechanism like that in Python.
The only natural and direct way to return newly created values (objects) from inside the function is to use the return command. However, a Python function does not limits you how many arguments can be returned. (Well, always a single one that can be later broken to elements if it was a tuple.)
If you want to test in the caller code what was actually returned, you can write your own function that does something special in cases where the following values were returned: None, single, a tuple of some length (len(t) can be used to get the number of elements in the returned tuple t). Your function can also test the type of single or of the each of the tuple elements and work accordingly.