Are multiple return values really harmful? (Re: determining the number of output arguments)

Hung Jung Lu hungjunglu at yahoo.com
Thu Nov 18 11:31:28 EST 2004


Carlos Ribeiro <carribeiro at gmail.com> wrote:
> 
> Dicts are not the best way to make it, because they are not ordered
> :-) But perhaps we could have something like "named tuples";
> 
> @returns('year','month','day')
> def today():
>     ...
>     return year, month, day

As someone has mentioned, usage of tuples is not very scalable and
tend to lend itself to carcass entries in the long run, or simply to
the breaking of compatibility. But I guess in your case, you want to
do something like printing out the results, so, as long as all items
are involved, an order would be beneficial.

------------------

For whatever it's worth, here are two more approaches for unordered
keyword argument and return.

(1) Usage of structures certainly is painful in C++, but not in
Python. What I often use is some generic object:

class Generic: pass

def today(p):
    print p.message
    r = Generic()
    r.year, r.month, r.day = 2004, 11, 18
    return r

p=Generic()
p.message = 'Hello!'
result = today(p)

I suspect a large number of people use this approach. Generic objects
are also good for pickling/serialization. (By the way, why is the new
style class "object()" made so that no dynamic attributes can be
assigned to it? Compared to dictionary, generic object is very helpful
as a syntax gadget and is used by many people. I am a bit surprised
that it's not part of the language. Why make so many people having to
resort to the "class Generic: pass" trick?)

(2) Use the function object itself:


def f():
    if not hasattr(f,'x'):
       f.x = 1
    else:
       f.x += 1
    f.y, f.z = 2*f.x, 3*f.x

f()
print f.x, f.y, f.z
f()
print f.x, f.y, f.z

Of course, this approach has more limited applicability. (Not good for
multithreaded case, not good for renaming the function object or
passing it around.)

Hung Jung



More information about the Python-list mailing list