Skip to content

CommandContext

Base classes

Name Children Inherits
Generic
typing
Abstract base class for generic types.

⋔ Inheritance diagram

graph TD
  2179016675["base.CommandContext"]
  3481597255["typing.Generic"]
  2751680898["builtins.object"]
  3481597255 --> 2179016675
  2751680898 --> 3481597255

🛈 DocStrings

Context passed to command handlers.

Class Type Parameters:

Name Bound or Constraints Description Default
TData

Type of the data available to commands. Access via get_data() for type-safe operations.

required
Source code in src/slashed/base.py
@dataclass
class CommandContext[TData]:
    """Context passed to command handlers.

    Type Parameters:
        TData: Type of the data available to commands. Access via get_data()
               for type-safe operations.
    """

    output: OutputWriter
    data: TData | None
    command_store: CommandStore
    metadata: dict[str, Any] = field(default_factory=dict)
    stdin: str = ""  # Input from pipe (previous command's stdout)

    async def print(self, message: str) -> None:
        """Write a message to output."""
        self.command_store.output.emit(message)
        if self.command_store.event_handler:
            event = CommandOutputEvent(context=self, output=message)
            await self.command_store.event_handler(event)
        await self.output.print(message)

    def get_data(self) -> TData:
        """deprecated: Use context instead."""
        return self.context

    @property
    def context(self) -> TData:
        """Get context data, asserting it's not None.

        Returns:
            The context data

        Raises:
            RuntimeError: If data is None
        """
        if self.data is None:
            msg = "Context data is None"
            raise RuntimeError(msg)
        return self.data

context property

context: TData

Get context data, asserting it's not None.

Returns:

Type Description
TData

The context data

Raises:

Type Description
RuntimeError

If data is None

get_data

get_data() -> TData

deprecated: Use context instead.

Source code in src/slashed/base.py
def get_data(self) -> TData:
    """deprecated: Use context instead."""
    return self.context

print async

print(message: str) -> None

Write a message to output.

Source code in src/slashed/base.py
async def print(self, message: str) -> None:
    """Write a message to output."""
    self.command_store.output.emit(message)
    if self.command_store.event_handler:
        event = CommandOutputEvent(context=self, output=message)
        await self.command_store.event_handler(event)
    await self.output.print(message)

:fa-brands-github: Show source on GitHub