Last active
September 9, 2020 08:13
-
-
Save meadsteve/0ff785b510e90f569e7b4ba7441264b9 to your computer and use it in GitHub Desktop.
Constrained types in python
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
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") |
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
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