O.rka
O.rka

Reputation: 30707

How to add set comprehension like union and intersect to Python class?

I want to create a class without inheriting frozenset (unless I can inherit both tuple and frozenset without getting TypeError: multiple bases have instance lay-out conflict) where I can use set comprehension like |, &, <, and > operators.

A = {"first"}
B = {"second"}
C = A | B

class Custom(tuple):
    def __new__(self, pair, **metadata):
        return super(Custom, self).__new__(self,tuple(pair))
    def __init__(self, pair, **metadata):
        self.pair = tuple(pair)
        self.metadata = metadata

pair_1 = Custom(["A","B"])
pair_2 = Custom(["B","C"])
pair_1 | pair_2

I couldn't find any "special" functions that do this.

Upvotes: 0

Views: 115

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599638

The special methods are all documented here; you need __and__, __or__, __lt__ and __gt__.

Upvotes: 2

Related Questions