0

Let's say I have a following piece of code

(x1, y1), (x2, y2) = foo()

class Bar:
    def __init__(self, x, y):
        self.x = x
        self.y = y

bar1 = Bar(x1, y1)
bar2 = Bar(x2, y2)

Is there any way to avoid having x1, x2 etc and unpack is directly to Bar instance, e.g. like this:

bar1 = Bar()
bar2 = Bar()

bar1, bar2 = foo()

I would expect some magic method like:

class Bar:  
    def __init__(self):
        self.x = None
        self.y = None
    def __unpack__(self, x, y):
        self.x = x
        self.y = y

But there is no such a method (or am I wrong?). How can I accomplish it another way?

Assume that foo is given and I cannot change it to return objects directly.

hans
  • 1,043
  • 12
  • 33

1 Answers1

1

Here's a way, but it's not particularly readable (I'm fond of tuplify though!)

def tuplify(seq, tuple_len): 
    """
    Groups elements of sequence to tuples of length tuple_len
    """
    return [tuple(el for idx, el in g[1]) for g in itertools.groupby(enumerate(seq), key=lambda x: x[0]//tuple_len)]

bar1, bar2 = (Bar(*tup) for tup in tuplify(foo(), 2)))
Yuri Feldman
  • 2,354
  • 1
  • 20
  • 23