Bases: OutputWriter
Output writer that directly delegates printing to a callback function.
The callback can be either sync or async and is fully responsible for how
the message is displayed/written.
Examples:
# Async callback
async def log_to_file(msg: str, file: str) -> None:
with open(file, "a") as f:
f.write(msg)
# Sync callback
def print_to_console(msg: str, prefix: str) -> None:
print(f"{prefix}: {msg}")
writer1 = CallbackOutputWriter(log_to_file, "output.log")
writer2 = CallbackOutputWriter(print_to_console, prefix="Debug")
Source code in src/slashed/output.py
| class CallbackOutputWriter(OutputWriter):
"""Output writer that directly delegates printing to a callback function.
The callback can be either sync or async and is fully responsible for how
the message is displayed/written.
Examples:
```python
# Async callback
async def log_to_file(msg: str, file: str) -> None:
with open(file, "a") as f:
f.write(msg)
# Sync callback
def print_to_console(msg: str, prefix: str) -> None:
print(f"{prefix}: {msg}")
writer1 = CallbackOutputWriter(log_to_file, "output.log")
writer2 = CallbackOutputWriter(print_to_console, prefix="Debug")
```
"""
def __init__(
self,
callback: Callable[..., Any | Awaitable[Any]],
*args: Any,
**kwargs: Any,
) -> None:
"""Initialize with callback and its arguments."""
self._callback = callback
self._args = args
self._kwargs = kwargs
async def print(self, message: str) -> None:
"""Write message using callback."""
result = self._callback(message, *self._args, **self._kwargs)
if inspect.isawaitable(result):
await result
|
__init__
__init__(callback: Callable[..., Any | Awaitable[Any]], *args: Any, **kwargs: Any) -> None
Initialize with callback and its arguments.
Source code in src/slashed/output.py
| def __init__(
self,
callback: Callable[..., Any | Awaitable[Any]],
*args: Any,
**kwargs: Any,
) -> None:
"""Initialize with callback and its arguments."""
self._callback = callback
self._args = args
self._kwargs = kwargs
|
print
async
print(message: str) -> None
Write message using callback.
Source code in src/slashed/output.py
| async def print(self, message: str) -> None:
"""Write message using callback."""
result = self._callback(message, *self._args, **self._kwargs)
if inspect.isawaitable(result):
await result
|