determining the number of output arguments

Fernando Perez fperez528 at yahoo.com
Mon Nov 15 00:57:15 EST 2004


Darren Dale wrote:

> I want to extend the capabilities of an existing function without breaking
> backward compatibility. I used nargin and nargout (number of arguments in
> and out) pretty extensively in Matlab.

Darren, I'm not a matlab expert, but I understand that matlab has a way of
knowing how many arguments a function output is being assigned to in any given
call.  Such functionality simply does not exist in python[*].  Depending
exactly on what you want to do, you can solve the problem in python in
different ways:

1. Pass a flag to your function:

def foo(x,nout=1):
  ...
  if nout==1:
     return a
  elif nout==2:
    return a,b
  else:
    return a,b,c

2. Unpack the output you want:

a,b,c = foo(x)[:3]

3. If you need only a few outputs, use throwaways:

a,_1,_2,b,_3,c=foo(x)  # ignore all _N vars

3. Or take all outputs, and extract only what you need:

out = foo(x)
a,b,c = out[2],out[13],out[356]

Best,

f

[*]  Since we do have real gurus in this group, I should qualify this.  I
suspect that by playing very nasty tricks with sys._getframe(), the dis and the
inspect modules, you probably _could_ get to this information, at least if the
caller is NOT a C extension module.  But I'm not even 100% sure this works, and
it would most certainly the kind of black magic I'm sure you are not asking
about.  But given the level of expertise here, I better cover my ass ;-)




More information about the Python-list mailing list