Last active
September 4, 2019 22:11
-
-
Save malcolmgreaves/98ad73b32bc82488c6ae3b9f0c3ad0c0 to your computer and use it in GitHub Desktop.
Data type for wrapping an indexed value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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