Sorted Containers Stubs

2.4.3 · active · verified Thu Apr 16

Community-maintained Python type stubs for the `sortedcontainers` library, which provides `dict`, `set`, and `list` data structures that automatically maintain the order of their elements by value. These stubs enable type checkers (like Mypy or Pyright) to enforce API details, including specific requirements for keys/values and special constructor return types, making `sortedcontainers` easier to use in type-checked codebases. The major and minor versions of `sortedcontainers-stubs` are designed to align with the corresponding major and minor versions of `sortedcontainers` itself. Current version is 2.4.3.

Common errors

Warnings

Install

Imports

Quickstart

Install `sortedcontainers-stubs` and then use `sortedcontainers` as usual with type hints. Type checkers will automatically discover the stubs. This example demonstrates basic usage of `SortedList`, `SortedDict`, and `SortedSet` with explicit type annotations.

from typing import List, Tuple
from sortedcontainers import SortedList, SortedDict, SortedSet

# Example with SortedList
def process_sorted_list(data: List[int]) -> SortedList[int]:
    sl = SortedList(data)
    sl.add(0)
    return sl

my_list: SortedList[int] = process_sorted_list([3, 1, 4, 1, 5])
print(f"SortedList: {my_list}")

# Example with SortedDict
def process_sorted_dict(data: List[Tuple[str, int]]) -> SortedDict[str, int]:
    sd = SortedDict(data)
    sd['apple'] = 100
    return sd

my_dict: SortedDict[str, int] = process_sorted_dict([('banana', 2), ('orange', 1)])
print(f"SortedDict: {my_dict}")

# Example with SortedSet
def process_sorted_set(data: List[int]) -> SortedSet[int]:
    ss = SortedSet(data)
    ss.add(10)
    return ss

my_set: SortedSet[int] = process_sorted_set([3, 1, 4, 1, 5])
print(f"SortedSet: {my_set}")

# To verify type checking, run a type checker like Mypy: `mypy your_script.py`
# The sortedcontainers-stubs package provides the type information for these objects.

view raw JSON →