4

C++17 introduced the new structured bindings syntax:

std::pair<int, int> p = {1, 2};
auto [a, b] = p;

Is there something similar in python3? I was thinking of using the "splat" operator to bind class variables to a list, which can be unpacked and assigned to multiple variables like such:

class pair:
    def __init__(self, first, second):
        self.first = first
        self.second = second
...

p = pair(1, 2)
a, b = *p

Is this possible? And if so, how would I go by implementing this to work for my own classes?

A tuple in Python works as a simple solution to this problem. However, built in types don't give much flexibility in implementing other class methods.

1
  • 2
    Are you looking for a tuple? p = (1, 2) a, b = p Commented Mar 14, 2022 at 23:00

3 Answers 3

6

Yes, you can use __iter__ method since iterators can be unpacked too:

class pair:
    def __init__(self, first, second):
        self.first = first
        self.second = second
    def __iter__(self):
        # Use tuple's iterator since it is the closest to our use case.
        return iter((self.first, self.second))

p = pair(1, 2)
a, b = p
print(a, b) # Prints 1 2
Sign up to request clarification or add additional context in comments.

2 Comments

a, b = *p still doesn't work with that.
yield self.first yield self.second might be a good alternative.
2

You can use tuples and tuple unpacking (see the bottom of this section in the Python documentation):

p = (1, 2)
a, b = p
print(a, b) # Prints 1 2

1 Comment

The problem with using built in types is that I can't implement other class methods, but thanks for the help.
1

An alternative with dataclass:

from dataclasses import dataclass, astuple

@dataclass
class pair:
    first: int
    second: int

p = pair(1, 2)
a, b = astuple(p)
print(a, b)

Output (Try it online!):

1 2

1 Comment

I would still be inclined to add def __iter__(self): return iter(astuple(self)) to remove the need for astuple call in user code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.