Skip to content

feat(commands): add support for typing.Literal[...] as command choices #2782

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ These changes are available on the `master` branch, but have not yet been releas
([#2714](https://github.com/Pycord-Development/pycord/pull/2714))
- Added the ability to pass a `datetime.time` object to `format_dt`
([#2747](https://github.com/Pycord-Development/pycord/pull/2747))
- Added support for `Literal[...]` to define command choices.
([#2782](https://github.com/Pycord-Development/pycord/pull/2782))

### Fixed

Expand Down
16 changes: 14 additions & 2 deletions discord/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@
from .options import Option, OptionChoice

if sys.version_info >= (3, 11):
from typing import Annotated, get_args, get_origin
from typing import Annotated, Literal, get_args, get_origin
else:
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import Annotated, Literal, get_args, get_origin

__all__ = (
"_BaseCommand",
Expand Down Expand Up @@ -805,6 +805,18 @@ def _parse_options(self, params, *, check_params: bool = True) -> list[Option]:
option = p_obj.annotation
if option == inspect.Parameter.empty:
option = str
if get_origin(option) is Literal:
literal_values = get_args(option)
if not all(isinstance(v, (str, int, float)) for v in literal_values):
raise TypeError(
"Literal values must be str, int, or float for Discord choices."
)
option = Option(
str,
choices=[
OptionChoice(name=str(v), value=str(v)) for v in literal_values
],
)

if self._is_typing_annotated(option):
type_hint = get_args(option)[0]
Expand Down