Skip to content

Order of overloads of index method can cause failure to type-check when a type is a sequence of itself (example: str) #100

Description

@startrekdude

First off, thank you for developing and maintaining this library! It's excellent and very useful. I have a minor bug to report.

Consider the following code:

from ordered_set import OrderedSet

oset: OrderedSet[str] = OrderedSet(["apple", "banana", "pear"])
apple_index: int = oset.index("apple")
print(oset[apple_index+1])

This should work—and it does! However, running mypy on it fails with the following error:

bug.py:4: error: Incompatible types in assignment (expression has type "list[int]", variable has type "int")  [assignment]

Why? Consider how the index method is defined:

@overload
def index(self, key: Sequence[T]) -> List[int]:
    ...

@overload
def index(self, key: T) -> int:
    ...

mypy sees we are calling index with a str and...this matches the first overload, as str is a Sequence[str]. mypy then concludes that the result is a list[int], causing the error.

The solution is to re-order the overloads so mypy sees, and uses, what is currently the second one. The actual implementation of index already does the right thing for strs.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions