Skip to content

Instantly share code, notes, and snippets.

@suvayu
Created March 12, 2020 17:42
Show Gist options
  • Save suvayu/3ab199d6e933fabd0ffc100a7873ac37 to your computer and use it in GitHub Desktop.
Save suvayu/3ab199d6e933fabd0ffc100a7873ac37 to your computer and use it in GitHub Desktop.
Types for numeric types with units and date ranges
from typing import Type
from pydantic import confloat, conint
"""
**kwargs for conint / confloat
strict: bool = False,
gt: float = None,
ge: float = None,
lt: float = None,
le: float = None,
multiple_of: float = None,
"""
def unitfloat(unit: str, **kwargs,) -> Type[float]:
namespace = dict(unit=unit)
confloat_t = confloat(**kwargs)
return type("UnitFloat", (confloat_t,), namespace)
def unitint(unit: str, **kwargs,) -> Type[int]:
namespace = dict(unit=unit)
conint_t = conint(**kwargs)
return type("UnitInt", (conint_t,), namespace)
"""
tuple of datetime stamps selecting a range of timesteps in the timeseries
"""
# TODO: finish
class DateRange:
def __init__(start, end):
self.start = start
self.end = end
# yield all validators (only one for now)
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def validate(cls):
if not isinstance(v, str):
raise TypeError("string required")
m = post_code_regex.fullmatch(v.upper())
if not m:
raise ValueError("invalid postcode format")
# you could also return a string here which would mean model.post_code
# would be a string, pydantic won't care but you could end up with some
# confusion since the value's type won't match the type annotation
# exactly
return cls(f"{m.group(1)} {m.group(2)}")
def __repr__(self):
return f"PostCode({super().__repr__()})"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment