Skip to content

fix: handling of Optional[...] in command option type resolution #2852

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 @@ -140,6 +140,8 @@ These changes are available on the `master` branch, but have not yet been releas
([#2843](https://github.com/Pycord-Development/pycord/pull/2843))
- Fixed `TypeError` when using `@option` with certain annotations and along with
`channel_types`. ([#2835](https://github.com/Pycord-Development/pycord/pull/2835))
- Fixed `TypeError` when using `Optional[...]` or `... | None` in command option type.
([#2852](https://github.com/Pycord-Development/pycord/pull/2852))

### Changed

Expand Down
24 changes: 23 additions & 1 deletion discord/commands/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@

import inspect
import logging
import types
from enum import Enum
from typing import TYPE_CHECKING, Literal, Optional, Type, Union
from typing import TYPE_CHECKING, Literal, Optional, Type, Union, get_args

from ..abc import GuildChannel, Mentionable
from ..channel import (
Expand Down Expand Up @@ -196,6 +197,7 @@ def __init__(
if self.name is not None:
self.name = str(self.name)
self._parameter_name = self.name # default
input_type = self._strip_none_type(input_type)
self._raw_type: InputType | tuple = input_type

enum_choices = []
Expand Down Expand Up @@ -365,6 +367,26 @@ def __init__(
if input_type is None:
raise TypeError("input_type cannot be NoneType.")

@staticmethod
def _strip_none_type(input_type):
if input_type is type(None):
raise TypeError("Option type cannot be only NoneType")

if isinstance(input_type, (types.UnionType, tuple)):
args = (
get_args(input_type)
if isinstance(input_type, types.UnionType)
else input_type
)
filtered = tuple(t for t in args if t is not type(None))
if not filtered:
raise TypeError("Option type cannot be only NoneType")
if len(filtered) == 1:
return filtered[0]
return filtered

return input_type

def to_dict(self) -> dict:
as_dict = {
"name": self.name,
Expand Down
Loading