feat: validate Literal[...] annotations as choices - #25
Merged
Conversation
bhirsz
force-pushed
the
feat/literal-choices
branch
from
August 30, 2026 12:59
4d6d812 to
1b89db5
Compare
Constrain an option or argument to a fixed set of values by annotating it
with typing.Literal[...]. Values are coerced to the members' type and then
checked for membership, raising OptionValueError otherwise. The allowed
values are surfaced in --help as a {a,b,c} metavar.
Refs #22
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
bhirsz
force-pushed
the
feat/literal-choices
branch
from
August 30, 2026 13:00
1b89db5 to
eeb4fb7
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Adds choice validation driven by
typing.Literal[...]annotations.Annotate an option (or argument) with
Literal[...]to restrict it to a fixedset of allowed values:
Behaviour
Literal[1, 2, 3]accepts the string
"2"from the CLI and yields2), then checked formembership.
OptionValueErrorlisting the allowed choices.list[Literal[...]],Literal[...] | None, methodvalueparameters, positional arguments, and TOML/env sources.
--helprenders the allowed values as a{a,b,c}metavar.Changes
coercion.py:ValueType.choices, Literal detection in_analyse,_analyse_literal, and membership enforcement incoerce_value.help.py: choices metavar.README.md: "Restricting a value to a set of choices" section.tests/test_choices.py: 10 tests.Refs #22
Part of the option-ergonomics stack: #23 (attribute typing) → #24 (default
factory) → this PR. Enables the PR #20 example to drop manual choice validation.