Skip to content

Commit

Permalink
Automatically casting the applied value to a string
Browse files Browse the repository at this point in the history
Signed-off-by: Stephen Bunn <[email protected]>
  • Loading branch information
stephen-bunn committed Jan 5, 2021
1 parent a5de581 commit 6b8ccdd
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
3 changes: 3 additions & 0 deletions changes/casting-values-to-string-automatically.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Automatically casting values applied to :class:`~chalky.chalk.Chalk` to strings.
This will fix issues where the user wants to easily use an instance of some class in a
templated string without having to cast it to a string themselves.
18 changes: 12 additions & 6 deletions src/chalky/chalk.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional, Set, Union, overload
from typing import Any, Optional, Set, Union, overload

from .color import Color_T
from .constants import is_disabled
Expand Down Expand Up @@ -76,24 +76,30 @@ def __and__(self, other: Chalk) -> Chalk:
background=other.background or self.background,
)

def __or__(self, value: str) -> str:
def __or__(self, value: Any) -> str:
"""Style some given string with the current chalk instance.
.. tip::
If a non-string value is provided, we will attempt to get the most
appropriate string from the value by simply calling ``str(value)``.
So if you are passing in an object, make sure to use an appropriate
``__str__`` or ``__repr__``.
Args:
value (str):
The string to apply the current chalk styles to.
value (~typing.Any):
The value to apply the current chalk styles to.
Returns:
str:
The newly styled string.
"""

if is_disabled():
return value
return str(value)

interface = get_interface()
return interface.apply(
value=value,
value=str(value),
style=self.style,
background=self.background,
foreground=self.foreground,
Expand Down
2 changes: 1 addition & 1 deletion src/chalky/interface/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def get_interface(io: Optional[TextIO] = None) -> BaseInterface:
This defaults to using :data:`sys.stdout`
>>> from chalky.interface import get_interface
>>> interface = get_iterface()
>>> interface = get_interface()
To get an interface using a different text io buffer, pass it in:
Expand Down

0 comments on commit 6b8ccdd

Please sign in to comment.