Skip to content

Instantly share code, notes, and snippets.

@purefunctor
Created June 23, 2021 15:41
Show Gist options
  • Save purefunctor/b055ccf3e3e1771472745b22f5ad6c68 to your computer and use it in GitHub Desktop.
Save purefunctor/b055ccf3e3e1771472745b22f5ad6c68 to your computer and use it in GitHub Desktop.
from typing import Generic, overload, Literal, TypeVar, Union
_Head = TypeVar("_Head")
_Tail = TypeVar("_Tail")
class HeadTuple(Generic[_Head, _Tail]):
def __init__(self, head: _Head, *tail: _Tail) -> None:
self._head = head
self._tail = tail
@overload
def __getitem__(self, index: Literal[0]) -> _Head:
...
@overload
def __getitem__(self, index: int) -> _Tail:
...
def __getitem__(self, index: Union[Literal[0], int]) -> Union[_Head, _Tail]:
if index == 0:
return self._head
else:
return self._tail[index]
f = HeadTuple("Hello", 1, 2, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment