Skip to content

place null last in anyOf for optional unions in JSON schema#1028

Open
SarthakB11 wants to merge 1 commit intojcrist:mainfrom
SarthakB11:fix/issue-1027
Open

place null last in anyOf for optional unions in JSON schema#1028
SarthakB11 wants to merge 1 commit intojcrist:mainfrom
SarthakB11:fix/issue-1027

Conversation

@SarthakB11
Copy link
Copy Markdown

Fixes #1027.

For T | None, _json_schema.py was emitting {"type": "null"} before
the struct/$ref entry in anyOf. Tools that pick the first anyOf
element for example generation (Swagger UI in the issue) ended up showing
null. Pydantic puts null last for the same reason.

Move NoneType out of the union iteration into a has_none flag and
append {"type": "null"} last in all three union branches (no-struct,
single-struct, tagged-struct). The tagged-struct branch's if options:
guard becomes if options or has_none: so Tagged | None keeps null
in its anyOf instead of dropping it.

Observable changes:

  • Struct | None: was [null, $ref], now [$ref, null].
  • Union[X, None, Y]: null moves from the middle to the end.
  • str | None: already [string, null] on CPython, unchanged.

Tests added in tests/unit/test_schema.py for Optional[Struct],
Union[int, None, str], and Union[Tagged, None] (covers the third
branch that previously dropped null entirely).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

field: Schema | None = None should generate anyOf where null is the last item

1 participant