简体   繁体   中英

Handy return values in Python

In Python, I would like to write a function that has a variable number of return values and that is easily dealt with. Something like

def test(a):
    if a > 0:
        return True
    else:
        return False, 123, 'foo'

can be used like

out = test(-5)

but a disadvantage I see here is that the user would have to check if the return argument is a tuple, and act accordingly. The meaning of the return values is not very explicit.

A variant would be to use dictionaries as return values but since I haven't ever seen this in any code, it feels a little hackish.

Are there better ways to organize the code?

but a disadvantage I see here is that the user would have to check if the return argument is a tuple, and act accordingly. The meaning of the return values is not very explicit.

In such scenario, always return a tuple , that would keep a consistency with handling the return type

>>> def test(a):
    if a > 0:
        return True,
    else:
        return False, 123, 'foo'

>>> out = test(-5)
>>> out
(False, 123, 'foo')
>>> out = test(1)
>>> out
(True,)

Always ensure that your return values are of a type which can be used consistently with each other.

In python, the type of a function is implicit. This means that the programmer can create a function of any type whatsoever (which is great), but it means that you, as a programmer have to take care to choose the type. In short: you should describe the return type in the docstring, and if it sounds like a bad idea, or a difficult function to use, it is.

The right thing here is either:

def test(a):
    ''' Always returns a 3-tuple, composed of Flag,data,data. Data may be None '''
    if a > 0:
        return True, None, None
    else:
        return False, 123, 'foo'

flag,data1,data2 = test(a)

or

def test(a):
    ''' Always returns a tuple, composed of a Flag, followed by 0 or more data items '''
    if a > 0:
        return True,
    else:
        return False, 123, 'foo'

return = test(a)
flag,rest = return[0],return[1:]
for x in rest: print x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM