Skip to content

Commit

Permalink
Fix is_optional(Literal[None])
Browse files Browse the repository at this point in the history
Without this, a field with a type like Literal[None, "a", "b"] may be considered required on some code paths.
In particular, when specifying a default for an argument group.
Note that this bug is difficult to work around because None | Literal["a", "b"] and Optional[Literal["a", "b"]] result in different (worse) parsing behavior.
  • Loading branch information
krzentner authored and lebrice committed Aug 28, 2024
1 parent b6c3346 commit ca35a25
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions simple_parsing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ def is_optional(t: type) -> bool:
bool
Whether or not this is an Optional.
>>> from typing import Union, Optional, List
>>> from typing import Union, Optional, List, Literal
>>> is_optional(str)
False
>>> is_optional(Optional[str])
Expand All @@ -519,8 +519,17 @@ def is_optional(t: type) -> bool:
False
>>> is_optional(Union[str, List, int, float, None])
True
>>> is_optional(Literal["a", None, "b"])
True
>>> is_optional(Literal["a", 1])
False
"""
return is_union(t) and type(None) in get_type_arguments(t)
if is_union(t) and type(None) in get_type_arguments(t):
return True
elif is_literal(t) and None in get_type_arguments(t):
return True
else:
return False


def is_tuple_or_list_of_dataclasses(t: type) -> bool:
Expand Down

0 comments on commit ca35a25

Please sign in to comment.