diff --git a/changes/casting-values-to-string-automatically.feature b/changes/casting-values-to-string-automatically.feature new file mode 100644 index 0000000..14c1966 --- /dev/null +++ b/changes/casting-values-to-string-automatically.feature @@ -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. diff --git a/src/chalky/chalk.py b/src/chalky/chalk.py index 9692d24..2efaa21 100644 --- a/src/chalky/chalk.py +++ b/src/chalky/chalk.py @@ -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 @@ -76,12 +76,18 @@ 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: @@ -89,11 +95,11 @@ def __or__(self, value: str) -> str: """ 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, diff --git a/src/chalky/interface/__init__.py b/src/chalky/interface/__init__.py index 97bf960..67560e0 100644 --- a/src/chalky/interface/__init__.py +++ b/src/chalky/interface/__init__.py @@ -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: