sharkyenergy
sharkyenergy

Reputation: 4173

TypeError: cannot unpack non-iterable GetColorImage object

i have following situation:

cratecolor.py: (code stripped to its minimum...)

import ... ...


class GetColorImage:  
    def __init__(self, ia=None):
        self.path = None
        self.img = None
        self.img0 = None
        self.s = None
        self.basetime = 0
        self.count = 0
        self.stride = 32
        self.ia = ia
        self.img_size = 640
        self.auto = True
        self.getImage()

    def getImage(self):
        self.ia.remote_device.node_map.ExposureTime.value = 350
        self.ia.remote_device.node_map.Gain.value = 150
    
        ...
        ...

        print(color, l)        # prints: 1 59.64829339143065

        return color, l

main.py: (code stripped to its minimum)

...
...

 # code exectued on a qthread:

 def getcolor(self, idin):
    color, lightness = cratecolor.GetColorImage(ia=self.ia) #******
    print(color, lightness)

In the line marked with ***** i get the error message color, lightness = cratecolor.GetColorImage(ia=self.ia) TypeError: cannot unpack non-iterable GetColorImage object but i dont get why. any help appreciated.

Upvotes: 1

Views: 185

Answers (3)

Alexander Jordan
Alexander Jordan

Reputation: 101

You're returning a GetColorImage object, not the two values you're actually looking for. The return statement in getImage() just returns the values to your constructor and does nothing with them. The constructor finishes and the whole GetColorImage object is returned. If you try to return something else from the constructor, you'll get an error.

You could just create the object and then call getImage():

colorObj = cratecolor.GetColorImage(ia=self.ia)
color, lightness = colorObj.getImage()

As pointed out below, you can just chain them if you don't need the object:

color, lightness = cratecolor.GetColorImage(ia=self.ia).getImage()

Upvotes: 1

Mechanic Pig
Mechanic Pig

Reputation: 7736

To unpack a object, you must ensure that it is iterable:

>>> class Foo:
...     def __iter__(self): return iter(range(2))
... 
>>> a, b = Foo()
>>> a
0
>>> b
1

So, you should make your class iteratable:

class GetColorImage:
    ...
    def __iter__(self):
        return iter(self.getImage())

Upvotes: 1

Lecdi
Lecdi

Reputation: 2241

You cannot return values from an __init__ function, so you instead must either:

  1. Call the getImage() method when creating the class
  2. Define an __iter__ method for the class to automatically allow you to assign it to multiple variables.

The second one is probably the better solution. Here is the method you would add to the class for it to work:

def __iter__(self):
    return iter(self.getImage())

Upvotes: 3

Related Questions