diff --git a/src/typesense/collections.py b/src/typesense/collections.py index 723b2de..72fa381 100644 --- a/src/typesense/collections.py +++ b/src/typesense/collections.py @@ -57,6 +57,34 @@ def __init__(self, api_call: ApiCall): self.api_call = api_call self.collections: typing.Dict[str, Collection[TDoc]] = {} + def __contains__(self, collection_name: str) -> bool: + """ + Check if a collection exists in Typesense. + + This method tries to retrieve the specified collection to check for its existence, + utilizing the Collection.retrieve() method but without caching non-existent collections. + + Args: + collection_name (str): The name of the collection to check. + + Returns: + bool: True if the collection exists, False otherwise. + """ + if collection_name in self.collections: + try: # noqa: WPS229, WPS529 + + self.collections[collection_name].retrieve() # noqa: WPS529 + return True + except Exception: + self.collections.pop(collection_name, None) + return False + + try: # noqa: WPS229, WPS529 + Collection(self.api_call, collection_name).retrieve() + return True + except Exception: + return False + def __getitem__(self, collection_name: str) -> Collection[TDoc]: """ Get or create a Collection instance for a given collection name. diff --git a/tests/collections_test.py b/tests/collections_test.py index 82f19ef..84971bd 100644 --- a/tests/collections_test.py +++ b/tests/collections_test.py @@ -293,3 +293,18 @@ def test_actual_retrieve( response[0].pop("created_at") assert response == expected + + +def test_actual_contains( + actual_collections: Collections, + delete_all: None, + create_collection: None, +) -> None: + """Test that the Collections object can check if a collection exists in Typesense.""" + # Test for existing collection + assert "companies" in actual_collections + + # Test for non-existing collection + assert "non_existent_collection" not in actual_collections + # Test again + assert "non_existent_collection" not in actual_collections