Skip to content

Commit

Permalink
model - nullable
Browse files Browse the repository at this point in the history
TypeAdapter can not be used in nested schemas and does not work with
delayed initialization/defer_build
pydantic/pydantic#8716
  • Loading branch information
commonism committed Feb 3, 2024
1 parent 6e71716 commit 1525b1b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
13 changes: 7 additions & 6 deletions aiopenapi3/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,26 +126,26 @@ def from_schema(
discriminators = []

r: List[Union[Type[BaseModel], Type[TypeAdapter]]] = list()

nullable = Model.is_nullable(schema)
for _type in Model.types(schema):
if _type == "null":
continue
r.append(Model.from_schema_type(schema, _type, schemanames, discriminators, extra))

if len(r) > 1:
ru: object = Union[tuple(r)]
if nullable:
ru = Optional[ru]
type_name = schema._get_identity("L8")
m: Type[RootModel] = pydantic.create_model(type_name, __base__=(RootModel[ru],), __module__=me.__name__)
elif len(r) == 1:
m: Type[BaseModel] = cast(Type[BaseModel], r[0])
if nullable:
type_name = schema._get_identity("L8")
m = pydantic.create_model(type_name, __base__=(RootModel[Optional[m]],), __module__=me.__name__)
else: # == 0
assert schema.type == "null"
return TypeAdapter(None.__class__)

if not isinstance(m, TypeAdapter) and Model.is_nullable(schema):
n = TypeAdapter(Optional[m])
return cast(Type[TypeAdapter], n)

return cast(Type[BaseModel], m)

@classmethod
Expand Down Expand Up @@ -323,6 +323,7 @@ def configof(schema: "SchemaType"):
return ConfigDict(
extra=extra_,
arbitrary_types_allowed=arbitrary_types_allowed_,
defer_build=True,
# validate_assignment=True
)

Expand Down
1 change: 1 addition & 0 deletions tests/schema_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,7 @@ def test_schema_ref_nesting(with_schema_ref_nesting):
("string", "a", "a", True),
("array", None, None, True),
("array", [], [], True),
("array", [None], [None], True),
],
)
def test_schema_nullable(with_schema_nullable, schema, input, output, okay):
Expand Down

0 comments on commit 1525b1b

Please sign in to comment.