dbt-labs / hologram

A library for automatically generating Draft 7 JSON Schemas from Python dataclasses
MIT License
9 stars 13 forks source link

support for restrictions, tests #21

Closed beckjake closed 5 years ago

beckjake commented 5 years ago

Allow for setting a restrict metadata member that restricts enums to a subset of a given enum. This will (I hope...) help hologram/jsonschema play nicely mypy, and obviate the need for StrLiteral anywhere (which doesn't pickle, causing Windows code involving multiprocessing.Process to fail in surprising and annoying ways).

Now you can define types as follows, and both mypy and hologram will be happy:

class MySelector(StrEnum):
    A = 'a'
    B = 'b'
    C = 'c'

@dataclass
class FancyRestrictBase(JsonSchemaMixin):
    foo: MySelector

@dataclass
class FancyRestrictATrue(FancyRestrictBase):
    foo: MySelector = field(metadata={'restrict': [MySelector.A]})
    is_something: bool = field(metadata={'restrict': [True]})
    bar: str

@dataclass
class FancyRestrictAFalse(FancyRestrictBase):
    foo: MySelector = field(metadata={'restrict': [MySelector.A]})
    is_something: bool = field(metadata={'restrict': [False]})
    bar: str

@dataclass
class FancyRestrictBC(FancyRestrictBase):
    foo: MySelector = field(metadata={'restrict': [MySelector.B, MySelector.C]})
    bar: str

@dataclass
class HasFancyRestricted(JsonSchemaMixin):
    thing: Union[FancyRestrictATrue, FancyRestrictAFalse, FancyRestrictBC]