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 23, 2024
1 parent 2d37d38 commit 2da716d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
19 changes: 15 additions & 4 deletions tests/test_type_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,11 +309,11 @@ 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])"
if sys.version_info >= (3, 9):
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,14 @@ 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(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]"
17 changes: 13 additions & 4 deletions type_lens/type_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,20 @@ 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:
if isinstance(self.annotation, type) or self.origin:
name = "Union" if self.is_optional else self.annotation.__name__
else:
name = repr(self.annotation)

if self.origin:
inner_types = ", ".join(t.repr_type for t in self.inner_types)
name = f"{name}[{inner_types}]"

return str(name)

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

0 comments on commit 2da716d

Please sign in to comment.