Created
February 18, 2025 14:01
-
-
Save skatenerd/343a7ab6b5181e02ae9ba1c9718f7c7d to your computer and use it in GitHub Desktop.
Nonempty List Types In Python
This file contains hidden or 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
# pyright: standard | |
from typing import TypeIs, reveal_type, TypeVar, Generic, Sequence, cast | |
T1 = TypeVar('T1') | |
Numeric = TypeVar('Numeric', bound=float) | |
class NonemptyTuple(tuple, Generic[T1]): | |
def __init__(self, *args, **kwargs): | |
raise ValueError("Never construct me directly") # Idk | |
pass | |
def has_items(items: tuple[T1, ...]) -> TypeIs[NonemptyTuple[T1]]: | |
return len(items) > 0 | |
class SafeMath(Generic[Numeric]): | |
def __init__(self, items: NonemptyTuple[Numeric]): | |
self.items = items | |
def headSafe(self) -> Numeric: | |
return self.items[0] | |
def rest(self) -> tuple[Numeric]: | |
rest: tuple[Numeric] = self.items[1:] | |
return rest | |
def max(self) -> Numeric: | |
head = self.headSafe() | |
rest = self.rest() | |
if has_items(rest): | |
return max(head, SafeMath(rest).max()) | |
else: | |
return head | |
items = tuple([1,99,2,3,4]) | |
if has_items(items): | |
print(SafeMath(items).max()) | |
# pretty cool that this is illegal!! | |
print(SafeMath(items).max()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment