Skip to content

Fix nested discriminated unions not discovered by env/CLI providers#816

Merged
hramezani merged 2 commits intomainfrom
fix/nested-discriminated-unions
Mar 16, 2026
Merged

Fix nested discriminated unions not discovered by env/CLI providers#816
hramezani merged 2 commits intomainfrom
fix/nested-discriminated-unions

Conversation

@hramezani
Copy link
Copy Markdown
Member

Summary

Fixes #815

  • _union_is_complex (utils.py): When a union arg is Annotated[Union[A, B], Discriminator(...)], _annotation_is_complex strips the Annotated wrapper and sees a bare Union[A, B], which it can't evaluate — returning False. The fix recurses into such inner unions while respecting Json metadata that intentionally suppresses complexity.
  • _CliArg.sub_models (cli.py): Extracted model collection into a recursive _collect_sub_models helper that walks nested unions to find all BaseModel/dataclass subclasses.

Test plan

  • Added test_nested_discriminated_union in test_settings.py — validates env vars with nested delimiter (a_or_b__x, a_or_b__b)
  • Added test_cli_nested_discriminated_union in test_source_cli.py — validates CLI args (--a_or_b.x, --a_or_b.b)
  • Existing test_json_field_with_discriminated_union still passes (Json metadata respected)
  • Existing test_env_union_with_complex_subfields_parses_plain_if_json_fails still passes (parse-failure fallback preserved)
  • Full test_settings.py (190 passed) and test_source_cli.py (169 passed) suites green

🤖 Generated with Claude Code

When a field uses `Annotated[Union[A, B], Discriminator(...)]`, the env
and CLI providers failed to discover the inner BaseModel subclasses
because `_union_is_complex` delegated to `_annotation_is_complex` which
doesn't handle bare Union types.  Similarly, `_CliArg.sub_models` only
checked immediate union args for model classes.

- `_union_is_complex`: after `_annotation_is_complex` returns False,
  recurse into inner unions (respecting Json metadata suppression).
- `_CliArg.sub_models`: extract model collection into a recursive
  `_collect_sub_models` helper that walks nested unions.

Fixes #815

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@hramezani hramezani force-pushed the fix/nested-discriminated-unions branch from 33f9526 to e02af20 Compare March 14, 2026 22:09
@hramezani hramezani enabled auto-merge (squash) March 16, 2026 09:30
@hramezani hramezani merged commit d10993e into main Mar 16, 2026
19 checks passed
@hramezani hramezani deleted the fix/nested-discriminated-unions branch March 16, 2026 09:32
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.

Nested discriminad Unions not registered correctly env/CLI providers

1 participant