determining the number of output arguments

Carl Banks imbosol at aerojockey.com
Tue Nov 16 09:08:00 CET 2004


Darren Dale <dd55 at cornell.edu> wrote in message news:<cn95k1$bfq$1 at news01.cit.cornell.edu>...
> 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.

Well, it's already been said that it's not possible without some black
magic.  There are other ways to accomplish what you want, more or
less, if you're open to other ideas.  When I find that I want to add
to a function, I typically do one of two things:

1. Add a flag in the argument list with a default value, like this:

    def function(a,b,c,new_behavior=False):
        pass

Adds new capibilities, does not affect backwards compatibility.  It's
also more explicit; you can see that something different is going on
from the call.  Having the number of return arguments determine the
function's behavior seems just a tad sneaky and backhanded to me.

2. Instead of adding capabilities to the function, refactor and write
an new function.  That is, take the stuff the stuff that's needed for
both the old and new capabilities, and put it into its own function. 
Then write two functions, one for the new and one for the old
capability, both of which call the refactored function.

Oftentimes, it just makes more sense for two different capabilities to
be in two different functions.

[And nowhere is the need for this more apparent than in the libraries
that ship with Matlab.  I use Matlab quite a bit at work, and nothing
about it annoys me more than the way they overload library functions
to the extreme (and that's saying a lot).  It's quite useful in some
cases, but why exactly do they need to cram 50 different nonlinear
programming methods, with all sorts of individualized options and
constraints, into one function?  (And this is AFTER they refactored
the optimization toolbox.)]


-- 
CARL BANKS



More information about the Python-list mailing list