Data description language for defining data models
pip3 install district42
from district42 import schema
UserSchema = schema.dict({
"id": schema.int.min(1),
"name": schema.str | schema.none,
"is_deleted": schema.bool,
})
print(UserSchema)
More powerful with:
And more
sch = schema.none
sch = schema.bool
sch = schema.bool(True)
sch = schema.int
sch = schema.int(42)
sch = schema.int.min(0)
sch = schema.int.max(0)
sch = schema.float
sch = schema.float(3.14)
sch = schema.float.min(0.0)
sch = schema.float.max(0.0)
sch = schema.str
sch = schema.str.len(10)
sch = schema.str.len(1, ...)
sch = schema.str.len(..., 32)
sch = schema.str.len(1, 32)
digits = "01234567890"
sch = schema.str.alphabet(digits)
sch = schema.str.contains("@")
import re
sch = schema.str.regex(r"[a-z]+")
sch = schema.list
sch = schema.list([schema.int(1), schema.int(2)])
sch = schema.list(schema.int)
sch = schema.list(schema.int).len(3)
sch = schema.list(schema.int).len(1, ...)
sch = schema.list(schema.int).len(..., 10)
sch = schema.list(schema.int).len(1, 10)
sch = schema.dict
sch = schema.dict({
"id": schema.int,
"name": schema.str | schema.none,
optional("platform"): schema.str,
})
sch = schema.any
sch = schema.any(schema.str, schema.int)
from typing import Any
from uuid import UUID
from district42 import Props, SchemaVisitor, SchemaVisitorReturnType as ReturnType
from district42.types import Schema
from niltype import Nilable
class UUIDProps(Props):
@property
def value(self) -> Nilable[UUID]:
return self.get("value")
class UUIDSchema(Schema[UUIDProps]):
def __accept__(self, visitor: SchemaVisitor[ReturnType], **kwargs: Any) -> ReturnType:
return visitor.visit_uuid(self, **kwargs)
def __call__(self, /, value: UUID) -> "UUIDSchema":
return self.__class__(self.props.update(value=value))
from typing import Any
from district42.representor import Representor
from niltype import Nil
class UUIDRepresentor(Representor, extend=True):
def visit_uuid(self, schema: UUIDSchema, *, indent: int = 0, **kwargs: Any) -> str:
r = f"{self._name}.uuid"
if schema.props.value is not Nil:
r += f"({schema.props.value!r})"
return r
from uuid import uuid4
from district42 import register_type, schema
register_type("uuid", UUIDSchema)
print(schema.uuid(uuid4()))
# schema.uuid(UUID('ce80d2b7-cdce-4e24-ab26-00c75471ce78'))
Full code available here: district42_exp_types/uuid