Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Last active September 4, 2019 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malcolmgreaves/98ad73b32bc82488c6ae3b9f0c3ad0c0 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/98ad73b32bc82488c6ae3b9f0c3ad0c0 to your computer and use it in GitHub Desktop.
Data type for wrapping an indexed value.
from typing import Generic, TypeVar, Union, Dict, Any, Type, cast
T = TypeVar("T")
class Indexed(Generic[T]):
__slots__ = ("_index", "_value")
def __init__(self, index: int, value: T) -> None:
self._index = index
self._value = value
@property
def index(self) -> int:
return self._index
@property
def value(self) -> T:
return self._value
def __str__(self) -> str:
return f"({self.index}, {self.value})"
def __eq__(self, other) -> bool:
return isinstance(other, Indexed) and other.index == self.index and other.value == self.value
def __hash__(self) -> int:
return hash(self.index) + 31 * hash(self.value)
def serialize_index(i: Indexed[T]) -> Dict[str, Union[int, T]]:
return {"index": i.index, "value": i.value}
def deserialize_index(value_type: Type[T], d: Dict[str, Any]) -> Indexed[T]:
return Indexed(index=d["index"], value=cast(value_type, d["value"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment