Skip to content

Commit

Permalink
Add dcargs.extras.literal_type_from_choices()
Browse files Browse the repository at this point in the history
  • Loading branch information
brentyi committed Oct 5, 2022
1 parent a04dfdd commit 7638c9e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions dcargs/extras/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
from .._argparse_formatter import set_accent_color
from .._cli import get_parser
from ._base_configs import subcommand_type_from_defaults
from ._choices_type import literal_type_from_choices
from ._serialization import from_yaml, to_yaml

__all__ = [
"set_accent_color",
"subcommand_type_from_defaults",
"get_parser",
"literal_type_from_choices",
"from_yaml",
"to_yaml",
]
18 changes: 18 additions & 0 deletions dcargs/extras/_choices_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import enum
from typing import Iterable, Type, TypeVar, Union

from typing_extensions import Literal

T = TypeVar("T", bound=Union[int, str, bool, enum.Enum])


def literal_type_from_choices(choices: Iterable[T]) -> Type[T]:
"""Generate a typing.Literal[] type that constrains values to a set of choices.
Using Literal[...] directly should generally be preferred, but this helper can be
used in the rare case that choices are generated dynamically. (for example, the keys
of a dictionary)
Using the returned type as an annotation currently breaks for mypy, but is
understood by Pyright."""
return Literal.__getitem__(tuple(choices)) # type: ignore

0 comments on commit 7638c9e

Please sign in to comment.