Skip to main content

Value substitutor for district42 schema

Project description


Codecov PyPI PyPI - Downloads Python Version

Value substitutor for district42 schema

(!) Work in progress, breaking changes are possible until v2.0 is released


pip3 install revolt


from district42 import schema
from revolt import substitute

UserSchema = schema.dict({
    "name": schema.str | schema.none,
    "id_deleted": schema.bool,

substituted = substitute(UserSchema, {"id": 1, "name": "Bob"})

# syntax sugar
substituted = UserSchema % {"id": 1, "name": "Bob"}


Custom Types

1. Declare Schema

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):
    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))

2. Register Substitutor

from typing import Any
from uuid import UUID
from niltype import Nil
from revolt import Substitutor

class UUIDSubstitutor(Substitutor, extend=True):
    def visit_uuid(self, schema: UUIDSchema, *, value: Any = Nil, **kwargs: Any) -> UUIDSchema:
        assert isinstance(value, UUID) and schema.props.value is Nil

        return schema.__class__(schema.props.update(value=value))

3. Register Representor

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

4. Use

from uuid import uuid4
from district42 import register_type, schema

register_type("uuid", UUIDSchema)

print(schema.uuid % uuid4())
# schema.uuid(UUID('8289806e-4f61-45a1-993b-1aa1b289735b'))

Full code available here: district42_exp_types/uuid

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

revolt-1.5.0.tar.gz (14.6 kB view hashes)

Uploaded Source

Built Distribution

revolt-1.5.0-py3-none-any.whl (20.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page