Created
November 13, 2021 15:18
-
-
Save zelaznik/a5b5c34d24cacc24ee0297a1305ad779 to your computer and use it in GitHub Desktop.
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 collections.abc import MutableSet | |
class SingleEntrySet(MutableSet): | |
"""\ | |
I created this class for debugging. It works like a regular set but it | |
raises an error if it tries to add an item that is already present. | |
""" | |
__slots__ = ("__items",) | |
def __init__(self, iterable=()): | |
MutableSet.__init__(self) | |
self.__items = set() | |
for item in iterable: | |
self.add(item) | |
def __contains__(self, item): | |
return item in self.__items | |
def __iter__(self): | |
return (item for item in self.__items) | |
def __len__(self): | |
return len(self.__items) | |
def add(self, item): | |
if item in self: | |
raise ValueError("item already in set: %r" % (item,)) | |
return self.__items.add(item) | |
def discard(self, item): | |
return self.__items.discard(item) | |
def __repr__(self): | |
return "%s({%s})" % (self.__class__.__name__, ", ".join(map(repr, self.__items))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment