Last active
March 28, 2025 15:10
-
-
Save jsbueno/4f28b2a058de87e0d76bad6eca844403 to your computer and use it in GitHub Desktop.
Python STrEnum whose members can be joined together with `|` resulting in a set.
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 StrEnum | |
class OrableStrEnum(StrEnum): | |
"""neat hack: Members can be combined with the `|` operator | |
That will result in a set - and then the `in` operator | |
is made to work with a single member as wll, so that | |
`if CAN_REVIEW in permissions:` will work whether permissions content is | |
permissions = CAN_REVIEW | |
or is | |
permissions = CAN_REVIEW | CAN_OVERWRITE | |
""" | |
def __or__(self, other): | |
if not isinstance(other, (set, type(self))): | |
return NotImplemented | |
if isinstance(other, set): | |
if not all(isinstance(item, type(self)) for item in other): | |
return NotImplemented | |
tmp = { | |
self, | |
} | |
tmp.update(other) | |
return tmp | |
return {other, self} | |
__ror__ = __or__ | |
def __contains__(self, item): | |
return item == self |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment