Skip to content

Commit

Permalink
feat: Add unwrap_optional method to TypeView.
Browse files Browse the repository at this point in the history
  • Loading branch information
DanCardin committed May 11, 2024
1 parent 2f8d9d5 commit df4e201
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
9 changes: 9 additions & 0 deletions tests/test_type_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,12 @@ def test_parsed_type_equality() -> None:
assert TypeView(list[int]) != TypeView(list[str])
assert TypeView(list[str]) != TypeView(tuple[str])
assert TypeView(Optional[str]) == TypeView(Union[str, None])


def test_unwrap_optional() -> None:
# Non-optionals should return the original input
assert TypeView(int).unwrap_optional() == TypeView(int)

assert TypeView(Optional[int]).unwrap_optional() == TypeView(int)
assert TypeView(Optional[Union[str, int]]).unwrap_optional() == TypeView(Union[str, int])
assert TypeView(Union[str, int, None]).unwrap_optional() == TypeView(Union[str, int])
13 changes: 12 additions & 1 deletion type_lens/type_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from collections import abc
from collections.abc import Collection, Mapping
from typing import Annotated, Any, AnyStr, Final, ForwardRef, TypeVar
from typing import Annotated, Any, AnyStr, Final, ForwardRef, TypeVar, Union

from typing_extensions import NotRequired, Required, get_args, get_origin

Expand Down Expand Up @@ -137,3 +137,14 @@ def has_inner_subclass_of(self, cl: type[Any] | tuple[type[Any], ...]) -> bool:
Whether any of the type's generic args are a subclass of the given type.
"""
return any(t.is_subclass_of(cl) for t in self.inner_types)

def unwrap_optional(self) -> TypeView:
if not self.is_optional:
return self

if len(self.args) == 2:
return TypeView(self.args[0])

args = tuple([a for a in self.args if a is not NoneType])
non_optional = Union[args]
return TypeView(non_optional)

0 comments on commit df4e201

Please sign in to comment.