dbt-labs / hologram

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

Fix union and some tuples #27

Closed beckjake closed 4 years ago

beckjake commented 4 years ago

This test fails without this change (with a frustrating validation error):

from dataclasses import dataclass
from typing import Tuple

from hologram import JsonSchemaMixin

@dataclass
class TupleMember(JsonSchemaMixin):
    a: int

@dataclass
class TupleMemberSecondHolder(JsonSchemaMixin):
    member: Tuple[str, TupleMember]

TupleMemberSecondHolder.from_dict({"member": ["a", {"a": 1}]})

hologram 0.0.6 only checks the first value in a Tuple's __args__, but tuples can be of two forms:

In the second form, tuple members beyond the first are not captured during schema generation.

hologram 0.0.6 also only checks the first member of a Union if one member is None (that's what is_optional checks). That generally works in the case of typing.Optional[T], as it becomes typing.Union[T, None]. But hologram does not handle weirder constructions like typing.Optional[typing.Union[None, T]] gracefully - that one gets stuck as typing.Union[None, T], so hologram doesn't generate schema information for T. The fix for this is to just remove all special handling of options when collecting field descriptions - the None values just fall through and you collect all the arguments.