Skip to content

Variable number of return arguments

Peter Corke edited this page Jun 22, 2020 · 2 revisions

Introduction

MATLAB allows functions to return a variable number of arguments, and the magic variable nargout specifies how many of those listed on the function signature line have been provided. For example

function [q,qd,qdd] = jtraj(q0, q1)

Can be called like

q = jtraj(q0, q1) % nargout = 1
[q,qd] = jtraj(q0, q1) % nargout = 2
[q,qd,qdd] = jtraj(q0, q1)  % nargout = 3

Python cannot do this, so we need some alternative.

Proposed convention

One Pythonic solution is to always return all three values as a tuple such as (q, qd, qdd).

However if we need just one element we need to write

out = jtraj(q0, q1)
q = out[0]

or

q,_,_ = jtraj(q0, q1)

or

q = jtraj(q0, q1)[0]

which is concise but a bit cryptic.

A better option might be to return a named tuple instead, for example

from collections import namedtuple

jt = namedtuple('jtraj', 'q qd qdd')

where jt is a namedtuple constructor

>>> x=jt(1,2,3)
>>> print(x)
jtraj(q=1, qd=2, qdd=3)
>>> x[1]
 2
>>> x.qdd
 3

Returning to our earlier example, if the function returns a namedtuple we can write

out = jtraj(q0, q1)
q = out.q

as well as the earlier idiom with the slice [0], but q is much more informative to the reader.

The concise version is now

q = jtraj(q0, q1).q

which is much less cryptic.

The return code of the function can also be quite concise

return namedtuple('jtraj', 'q qd qdd')(q, qd, qdd)

There is maybe some wasted time to compute things that are not needed. If some outputs were particularly expensive we could use keyword boolean arguments to control their computation and addition to the returned tuple.