Skip to content

Commit 2cf71df

Browse files
Lumabotspre-commit-ci[bot]Lulalaby
authored
fix: handling of Optional[...] in command option type resolution (#2852)
Signed-off-by: Lumouille <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Lala Sabathil <[email protected]>
1 parent 3f2fb34 commit 2cf71df

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ These changes are available on the `master` branch, but have not yet been releas
161161
([#2843](https://github.com/Pycord-Development/pycord/pull/2843))
162162
- Fixed `TypeError` when using `@option` with certain annotations and along with
163163
`channel_types`. ([#2835](https://github.com/Pycord-Development/pycord/pull/2835))
164+
- Fixed `TypeError` when using `Optional[...]` or `... | None` in command option type.
165+
([#2852](https://github.com/Pycord-Development/pycord/pull/2852))
164166
- Fixed type-hinting for `PermissionOverwrite.update`.
165167
([#2878](https://github.com/Pycord-Development/pycord/pull/2878))
166168
- Fixed `AttributeError` when accessing `AuditLogEntry.changes` more than once.

discord/commands/options.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,9 @@
2626

2727
import inspect
2828
import logging
29+
import types
2930
from enum import Enum
30-
from typing import TYPE_CHECKING, Literal, Optional, Type, Union
31+
from typing import TYPE_CHECKING, Literal, Optional, Type, Union, get_args
3132

3233
from ..abc import GuildChannel, Mentionable
3334
from ..channel import (
@@ -196,6 +197,7 @@ def __init__(
196197
if self.name is not None:
197198
self.name = str(self.name)
198199
self._parameter_name = self.name # default
200+
input_type = self._strip_none_type(input_type)
199201
self._raw_type: InputType | tuple = input_type
200202

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

370+
@staticmethod
371+
def _strip_none_type(input_type):
372+
if input_type is type(None):
373+
raise TypeError("Option type cannot be only NoneType")
374+
375+
if isinstance(input_type, (types.UnionType, tuple)):
376+
args = (
377+
get_args(input_type)
378+
if isinstance(input_type, types.UnionType)
379+
else input_type
380+
)
381+
filtered = tuple(t for t in args if t is not type(None))
382+
if not filtered:
383+
raise TypeError("Option type cannot be only NoneType")
384+
if len(filtered) == 1:
385+
return filtered[0]
386+
return filtered
387+
388+
return input_type
389+
368390
def to_dict(self) -> dict:
369391
as_dict = {
370392
"name": self.name,

0 commit comments

Comments
 (0)