Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structured bindings in Python

Tags:

c++

python

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.

like image 795
Blackgaurd Avatar asked Sep 02 '25 03:09

Blackgaurd


1 Answers

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
like image 118
Quimby Avatar answered Sep 04 '25 16:09

Quimby