0

How to protect against such a situation? if x=1 its OK, but when x=0:

def test():

    x=0
    if (x == 0): return 0
    else:
        return 'abc', 100, 200


a, b, c = test()
print(b)

TypeError: cannot unpack non-iterable int object.

Maybe such a solution would be better ?

class ReturnValue:
    def __init__(self):
        self.a = "a"
        self.b = 100
        self.c = 200

def test():
    return ReturnValue()

t = test()
if (t):
    print("%s, %s, %s" % (t.a,t.b,t.c))
else:
    print("error")
thomas
  • 11
  • 2

3 Answers3

0

It's generally a bad idea to return variable number of values but this is how you can do it:

def test():
    x=0
    if (x == 0): return (0,)
    return 'abc', 100, 200

vals = test()
if len(vals) == 1:
    a = vals[0]
elif len(vals) == 3:
    a,b,c = vals

Reference: https://stackoverflow.com/a/30703804/6912045

Se7eN
  • 548
  • 1
  • 7
  • 22
0

In general, it's a good idea to keep the signature of a function consistent, meaning that it always returns the same number and type of values. What you've implemented here return a single int in one case and a tuple of integers in another.

Returning 1 value when 3 are expected, cannot work.

You could throw and exception for the case of 0, otherwise there's the option to return a tuple, where the first element signifies the status of the function, as described here: https://stackoverflow.com/a/1630722/2823986

mxschumacher
  • 37
  • 1
  • 7
0

I can see that you are getting this error "TypeError: cannot unpack non-iterable int object" because in the return statement of "X=0" have returned value i.e. 0 but it should be 0,0,0 as you want to assign three values a,b,c.

Try the below code, it will solve your error:

def test():

x=0
if (x == 0): return 0,0,0
else:
    return 'abc', 100, 200

a, b, c = test() print(b)

Code run
  • 165
  • 9