Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Experimenting with Pydantic dataclasses #4

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions dc_schema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import dataclasses
import numbers
import typing as t

from types import UnionType

_MISSING = dataclasses.MISSING

Expand Down Expand Up @@ -132,7 +132,8 @@ def create_dc_schema(self, dc):
def get_field_schema(self, type_, default, annotation):
if dataclasses.is_dataclass(type_):
return self.get_dc_schema(type_, annotation)
if t.get_origin(type_) == t.Union:
# NOTE: Fixes pydantic dataclass unions
if t.get_origin(type_) in (t.Union, UnionType):
return self.get_union_schema(type_, default, annotation)
if t.get_origin(type_) == t.Literal:
return self.get_literal_schema(type_, default, annotation)
Expand All @@ -154,6 +155,9 @@ def get_field_schema(self, type_, default, annotation):
return self.get_bool_schema(default, annotation)
elif type_ == int:
return self.get_int_schema(default, annotation)
# FIXME: Do not validate Any
elif type_ == t.Any:
return annotation.schema()
elif issubclass(type_, numbers.Number):
return self.get_number_schema(default, annotation)
elif issubclass(type_, enum.Enum):
Expand Down Expand Up @@ -197,7 +201,8 @@ def get_dict_schema(self, type_, annotation):
args = t.get_args(type_)
assert len(args) in (0, 2)
if args:
assert args[0] == str
# FIXME: Could also be enums
# assert args[0] == str
return {
"type": "object",
"additionalProperties": self.get_field_schema(
Expand All @@ -223,6 +228,12 @@ def get_list_schema(self, type_, annotation):
def get_tuple_schema(self, type_, default, annotation):
if default is _MISSING:
schema = {**annotation.schema()}
# FIXME: Pydantic dataclasses
elif default.__class__.__name__ == 'FieldInfo':
if str(default.default) == 'PydanticUndefined':
schema = {**annotation.schema()}
else:
schema = {"default": list(default.default), **annotation.schema()}
else:
schema = {"default": list(default), **annotation.schema()}
args = t.get_args(type_)
Expand Down