typesense-python icon indicating copy to clipboard operation
typesense-python copied to clipboard

[types] incomptabile assignment types due to invariant and type union

Open rchui opened this issue 8 months ago • 3 comments

Instead of using type unions (like used here https://github.com/typesense/typesense-python/blob/master/src/typesense/types/collection.py#L226-L232), the library should use bound typevar like:

a: list[int | str]
b: list[int] = [1]

a = b  # failure: incompatible assignment due to invariant

from typing import TypeVar

ListT = TypeVar("ListT", bound=int | str)

c: list[ListT]
d: list[int] = [1]
e: list[str] = ["a"]
f: list[int | str] = [1, "a"]

c = d  # success
c = e  # success
c = f  # success

The type checkers are really unhappy with the way that the types are currently formulated. I should be able to supply a list of just RegularCollectionFieldSchema to CollectionUpdateSchema. Instead it errors due to the type construction. I shouldn't have to reverse engineer the internal union type to satisfy the type checker.

rchui avatar Jun 17 '25 17:06 rchui

That's due to the nominality of the type system. The solution you propose involves generating generics for all possible unions, and we can take a look into making those changes. Any other places where you've noticed this behavior, apart from the collection update operation?

tharropoulos avatar Jun 17 '25 17:06 tharropoulos

Collection create operation also gives me a similar error: https://github.com/typesense/typesense-python/blob/master/src/typesense/types/collection.py#L176

I'm sure there are others too

rchui avatar Jun 17 '25 19:06 rchui

@tharropoulos I ended up working around this by adding a bunch of type: ignore comments. This change would still be highly appreciated.

rchui avatar Nov 15 '25 16:11 rchui