This repository has been archived by the owner on Aug 19, 2023. It is now read-only.
Change behavior of typing.Optional (create optional, nullable field) #56
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi @s-knibbs ,
Thanks for building and maintaining this package. I spent some time evaluating it today and noticed a surprising interaction between typing.Optional and how nullable fields are treated in JSON schema. So, I put together a small proof of concept of what a different approach might look like for discussion.
The thing that specifically surprised me is that according to the typing.Optional documentation, Optional is simply an alias for
Union[..., None]
. With defaults, this lets you null a field to indicate a value is not present, or apply a default value. With that in mind, I would expect the following code to work:The above code fails with:
Which is a somewhat surprising way to fail, given that the default value for
id
isNone
!Digging into internals here, it seems like a better way to represent
Optional[int]
is similarly to how you representUnion[str, int]
, except withNone
/null
as a first class type. This branch changes the schema generator to useoneOf: [{type: integer}, {type: null}]
in addition to marking the field as not required. I think this better approximates how I'd expect the JSON schema to look. (although it would be a lot better if there were a way to separately define the field as required vs. nullable, I just don't think typing has a good syntax for that.)One downside is that this branch in its current state breaks SWAGGER_V2 schema generation. I could modify this to conditionally revert to the old way of generating Optional schemas for SWAGGER_V2. Then this change would only apply to openapi 3 / swagger 3 / json schema.
Let me know what you think & thanks for your time.