Skip to content

Commit fbe6d94

Browse files
authored
Merge pull request #85 from tharropoulos/contains-dunder
feat(collections): add `__contains__` method for collection existence
2 parents 58df75e + f59ac37 commit fbe6d94

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/typesense/collections.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,34 @@ def __init__(self, api_call: ApiCall):
5757
self.api_call = api_call
5858
self.collections: typing.Dict[str, Collection[TDoc]] = {}
5959

60+
def __contains__(self, collection_name: str) -> bool:
61+
"""
62+
Check if a collection exists in Typesense.
63+
64+
This method tries to retrieve the specified collection to check for its existence,
65+
utilizing the Collection.retrieve() method but without caching non-existent collections.
66+
67+
Args:
68+
collection_name (str): The name of the collection to check.
69+
70+
Returns:
71+
bool: True if the collection exists, False otherwise.
72+
"""
73+
if collection_name in self.collections:
74+
try: # noqa: WPS229, WPS529
75+
76+
self.collections[collection_name].retrieve() # noqa: WPS529
77+
return True
78+
except Exception:
79+
self.collections.pop(collection_name, None)
80+
return False
81+
82+
try: # noqa: WPS229, WPS529
83+
Collection(self.api_call, collection_name).retrieve()
84+
return True
85+
except Exception:
86+
return False
87+
6088
def __getitem__(self, collection_name: str) -> Collection[TDoc]:
6189
"""
6290
Get or create a Collection instance for a given collection name.

tests/collections_test.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,3 +293,18 @@ def test_actual_retrieve(
293293

294294
response[0].pop("created_at")
295295
assert response == expected
296+
297+
298+
def test_actual_contains(
299+
actual_collections: Collections,
300+
delete_all: None,
301+
create_collection: None,
302+
) -> None:
303+
"""Test that the Collections object can check if a collection exists in Typesense."""
304+
# Test for existing collection
305+
assert "companies" in actual_collections
306+
307+
# Test for non-existing collection
308+
assert "non_existent_collection" not in actual_collections
309+
# Test again
310+
assert "non_existent_collection" not in actual_collections

0 commit comments

Comments
 (0)