matplotlib.mlab.find() not quite like Matlab"s

I guess there is no way in Python of emulating

>Matlab"s detection of the number of output arguments.

I just got a response from c.l.p. Somebody remembered seeing this at ASPN:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/284742

expecting() is the workhorse, equivalent to Matlab's nargout:

import inspect,dis

def expecting():
    """Return how many values the caller is expecting"""
    f = inspect.currentframe()
    f = f.f_back.f_back
    c = f.f_code
    i = f.f_lasti
    bytecode = c.co_code
    instruction = ord(bytecode[i+3])
    if instruction == dis.opmap['UNPACK_SEQUENCE']:
        howmany = ord(bytecode[i+4])
        return howmany
    elif instruction == dis.opmap['POP_TOP']:
        return 0
    return 1

def cleverfunc():
    howmany = expecting()
    if howmany == 0:
        print "return value discarded"
    if howmany == 2:
        return 1,2
    elif howmany == 3:
        return 1,2,3
    return 1

def test():
    cleverfunc()
    x = cleverfunc()
    print x
    x,y = cleverfunc()
    print x,y
    x,y,z = cleverfunc()
    print x,y,z

test()

Darren Dale wrote:

>I guess there is no way in Python of emulating
>Matlab"s detection of the number of output arguments.

I just got a response from c.l.p. Somebody remembered seeing this at ASPN:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/284742

expecting() is the workhorse, equivalent to Matlab's nargout:

Very cool. but I'd caution against using it. I'd much rather see matplotlib be pythonesque than an exact duplicate of MATLAB. This is NOT pythonesque!

Precisely speaking, python functions ALWAYS return just one object: A tuple. That tuple can contain any number of other objects, and sequence unpacking means it can look like you're returning multiple values, but you're not really. i.e.

def test():
  return (1,2,3) # same as return 1,2,3

# now call it:

a,b,c = test()
(a,b,c) = test()
x = test(); a,b,c = x
x = test(); a = x[0]; b = x[1]; c = x[2]

# Are all equivalent

if one uses the last two forms, expecting() will break.

-Chris

···

--
Christopher Barker, Ph.D.
Oceanographer
                                         
NOAA/OR&R/HAZMAT (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception

Chris.Barker@...259...