Skip to content

Commit

Permalink
feat: Add repr_type helper method to TypeView.
Browse files Browse the repository at this point in the history
  • Loading branch information
DanCardin committed Jun 12, 2024
1 parent 2d37d38 commit 0eeb542
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
18 changes: 15 additions & 3 deletions tests/test_type_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,10 +310,10 @@ def test_strip_optional() -> None:
def test_repr() -> None:
assert repr(TypeView(int)) == "TypeView(int)"
if sys.version_info < (3, 9):
assert repr(TypeView(Optional[str])) == "TypeView(typing.Union[str, NoneType])"
assert repr(TypeView(Optional[str])) == "TypeView(Union[str, NoneType])"
else:
assert repr(TypeView(Optional[str])) == "TypeView(typing.Optional[str])"
assert repr(TypeView(Literal["1", 2, True])) == "TypeView(typing.Literal['1', 2, True])"
assert repr(TypeView(Optional[str])) == "TypeView(Optional[str])"
assert repr(TypeView(Literal["1", 2, True])) == "TypeView(Literal['1', 2, True])"


def test_is_none_type() -> None:
Expand Down Expand Up @@ -354,3 +354,15 @@ def test_safe_generic_origin(annotation: Any, expected: Any) -> None:
if isinstance(annotation, str):
annotation = eval(annotation)
assert TypeView(annotation).safe_generic_origin is expected


def test_repr_type() -> None:
assert TypeView(int).repr_type == "int"
assert TypeView(str).repr_type == "str"
assert TypeView("asdf").repr_type == "asdf"
assert TypeView(Optional[int]).repr_type in ("Optional[int]", "Union[int, NoneType]", "Union[int, None]")
assert TypeView(Literal[1, "two"]).repr_type == "Literal[1, 'two']"
assert TypeView(Union[Literal[1, "two"], bool]).repr_type == "Union[Literal[1, 'two'], bool]"

if sys.version_info >= (3, 9):
assert TypeView(set[bool]).repr_type == "set[bool]"
12 changes: 8 additions & 4 deletions type_lens/type_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,15 @@ def __eq__(self, other: object) -> bool:

def __repr__(self) -> str:
cls_name = self.__class__.__name__
return f"{cls_name}({self.repr_type})"

raw = self.raw
if isinstance(self.raw, type):
raw = raw.__name__ # type: ignore[attr-defined]
return f"{cls_name}({raw})"
@property
def repr_type(self) -> str:
ann = self.annotation
if isinstance(ann, type) and not self.origin:
ann = ann.__name__ # type: ignore[attr-defined]

return str(ann).replace("typing.", "")

@property
def allows_none(self) -> bool:
Expand Down

0 comments on commit 0eeb542

Please sign in to comment.