Skip to content

Commit

Permalink
Add __contains__ method (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbrochart authored Jan 4, 2024
1 parent a3df330 commit 3860a73
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
3 changes: 3 additions & 0 deletions python/pycrdt/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,9 @@ def __getitem__(self, key: int) -> BaseType:
def __iter__(self):
return ArrayIterator(self)

def __contains__(self, item: Any) -> bool:
return item in iter(self)

def __str__(self) -> str:
with self.doc.transaction() as txn:
return self.integrated.to_json(txn._txn)
Expand Down
3 changes: 3 additions & 0 deletions python/pycrdt/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ def __setitem__(self, key: str, value: Any) -> None:
def __iter__(self):
return self.keys()

def __contains__(self, item: str) -> bool:
return item in self.keys()

def get(self, key: str, default_value: Any | None = None) -> Any | None:
with self.doc.transaction():
if key in self.keys():
Expand Down
21 changes: 21 additions & 0 deletions python/pycrdt/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ def _init(self, value: str | None) -> None:
def _get_or_insert(self, name: str, doc: Doc) -> _Text:
return doc._doc.get_or_insert_text(name)

def __iter__(self):
return TextIterator(self)

def __contains__(self, item: str) -> bool:
return item in str(self)

def __len__(self) -> int:
with self.doc.transaction() as txn:
return self.integrated.len(txn._txn)
Expand Down Expand Up @@ -129,5 +135,20 @@ class TextEvent(BaseEvent):
__slots__ = "target", "delta", "path"


class TextIterator:
def __init__(self, text: Text):
self.text = text
self.length = len(text)
self.idx = 0

def __next__(self):
if self.idx == self.length:
raise StopIteration

res = self.text[self.idx]
self.idx += 1
return res


base_types[_Text] = Text
event_types[_TextEvent] = TextEvent

0 comments on commit 3860a73

Please sign in to comment.