Last active
June 30, 2022 20:53
-
-
Save Kenny2github/28239983d923c75bf61b5e7682f6f63c to your computer and use it in GitHub Desktop.
An enum.Flag subclass that supports all frozenset operations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Flag | |
class SetLikeFlag(Flag): | |
"""Flag that additionally supports all frozenset operations.""" | |
def __repr__(self): | |
"""Only show the flag names, not values.""" | |
return super().__repr__().split(':', 1)[0] + '>' | |
def __sub__(self, other): | |
"""Asymmetric difference of this set of flags with the other.""" | |
if not isinstance(other, type(self)): | |
return NotImplemented | |
return self & ~other | |
def __le__(self, other): | |
"""Whether this set of flags is a subset of the other.""" | |
if not isinstance(other, type(self)): | |
return NotImplemented | |
return (self & other) == self | |
def __lt__(self, other): | |
"""Whether this set of flags is a proper subset of the other.""" | |
if not isinstance(other, type(self)): | |
return NotImplemented | |
return self <= other and self != other | |
def __ge__(self, other): | |
"""Whether this set of flags is a superset of the other.""" | |
return other <= self | |
def __gt__(self, other): | |
"""Whether this set of flags is a proper superset of the other.""" | |
return other < self |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import auto | |
from set_like_flag import SetLikeFlag | |
class U(SetLikeFlag): | |
"""Definition of the universe.""" | |
A = auto() | |
B = auto() | |
C = auto() | |
D = auto() | |
def test_set_like_flag(): | |
# operator precedence dictates these parentheses | |
assert (U.A|U.B|U.C) - (U.B|U.C|U.D) == U.A, "incorrect asymmetric difference" | |
assert U.A|U.B <= U.A|U.B|U.C, "should be subset" | |
assert U.A|U.B < U.A|U.B|U.C, "should be proper subset" | |
assert U.A|U.B|U.C <= U.A|U.B|U.C, "should be subset" | |
assert not (U.A|U.B|U.C < U.A|U.B|U.C), "shouldn't be proper subset" | |
assert not (U.A|U.B|U.D <= U.A|U.B|U.C), "shouldn't be subset" | |
assert U.A|U.B|U.C >= U.A|U.B, "should be superset" | |
assert U.A|U.B|U.C > U.A|U.B, "should be proper superset" | |
assert U.A|U.B|U.C >= U.A|U.B|U.C, "should be superset" | |
assert not (U.A|U.B|U.C > U.A|U.B|U.C), "shouldn't be proper superset" | |
assert not (U.A|U.B|U.C >= U.A|U.B|U.D), "shouldn't be superset" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment