Skip to content

Instantly share code, notes, and snippets.

@meadsteve
Last active September 9, 2020 08:13
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 meadsteve/0ff785b510e90f569e7b4ba7441264b9 to your computer and use it in GitHub Desktop.
Save meadsteve/0ff785b510e90f569e7b4ba7441264b9 to your computer and use it in GitHub Desktop.
Constrained types in python
class NonEmptyList(list, Generic[T]):
def __init__(self, *members: T):
super().__init__([*members])
self._validate_constraints()
def _validate_constraints(self):
if len(self) < 1:
raise RuntimeError("NonEmptyList must have at least one member")
class PositiveInteger(int):
def __init__(self, value):
super().__init__()
if self <= 0:
raise RuntimeError("Positive integers must be positive")
if float(self) != float(value):
raise RuntimeError(f"{value} is not an integer")
class PositiveFloat(float):
def __init__(self, value):
super().__init__()
if self <= 0:
raise RuntimeError("Positive floats must be positive")
if float(self) != float(value):
raise RuntimeError(f"{value} is not a valid float")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment