Skip to content

Commit

Permalink
support converting objects to string
Browse files Browse the repository at this point in the history
  • Loading branch information
abrahammurciano committed May 21, 2024
1 parent d6fd2ba commit 9de037a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
10 changes: 7 additions & 3 deletions constyle/_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,15 @@ def __init__(
self._prefix = f"\033[{';'.join(str(p) for p in self._params)}m"
self._end = end

def __call__(self, string: str) -> str:
def __call__(self, string: object) -> str:
"""Apply this style to the given string.
If the given object isn't a string it will be converted into one.
Args:
string: The string to apply the style to.
"""
return f"{self}{string}{self._end or Style()}" if string else string
return f"{self}{string}{self._end or Style()}" if string != "" else string

def __add__(self, other: "Style") -> "Style":
"""Add the attributes of the left and right `Style` operands, returning a new `Style`.
Expand All @@ -72,9 +74,11 @@ def __eq__(self, __o: object) -> bool:
)


def style(string: str, *attrs: "Style", end: "Optional[Style]" = None) -> str:
def style(string: object, *attrs: "Style", end: "Optional[Style]" = None) -> str:
"""Apply the given attributes to the given string.
If the given object isn't a string it will be converted into one.
Args:
string: The string to style.
*attrs: The attributes/styles to apply.
Expand Down
4 changes: 4 additions & 0 deletions tests/test_constyle.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,7 @@ def test_add() -> None:

def test_attribute_call() -> None:
assert Attributes.BOLD("Hello World") == style("Hello World", Attributes.BOLD)


def test_non_string() -> None:
assert style(None, Attributes.BOLD) == style("None", Attributes.BOLD)

0 comments on commit 9de037a

Please sign in to comment.