Last active
July 25, 2020 07:02
-
-
Save Niraj-Kamdar/0bed6b9895b96b7ea632e72583e66336 to your computer and use it in GitHub Desktop.
Recipe for MutableSet
This file contains 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
""" | |
filename: mutable_set.py | |
author: Niraj Kamdar | |
""" | |
import weakref | |
from collections import abc | |
from typing import Iterator, List, Any | |
class MutableSet(abc.MutableSet, abc.Mapping): | |
def __init__(self, iterable=None): | |
self.set = {} | |
if iterable: | |
self.set = {i: weakref.ref(i) for i in iterable} | |
def add(self, x: Any) -> None: | |
if x not in self.set: | |
self.set[x] = weakref.ref(x) | |
def discard(self, x: Any) -> None: | |
if x in self.set: | |
del self.set[x] | |
def remove(self, x: Any) -> None: | |
if x not in self.set: | |
raise KeyError(x) | |
del self.set[x] | |
def __contains__(self, x: Any) -> bool: | |
return x in self.set | |
def __len__(self) -> int: | |
return len(self.set) | |
def __repr__(self) -> str: | |
return f"{{{', '.join(map(str, self.set.keys())).rstrip(', ')}}}" | |
def __iter__(self) -> Iterator[Any]: | |
return iter(self.set) | |
def __getitem__(self, k: Any) -> Any: | |
return self.set[k]() | |
def get(self, k: Any, default=None) -> Any: | |
if k in self.set: | |
return self.set[k]() | |
return default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment