Skip to content

Command

Base classes

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

⋔ Inheritance diagram

graph TD
  1376813048["base.Command"]
  900363605["base.BaseCommand"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  3481597255["typing.Generic"]
  900363605 --> 1376813048
  925645236 --> 900363605
  2751680898 --> 925645236
  3481597255 --> 1376813048
  2751680898 --> 3481597255

🛈 DocStrings

Bases: BaseCommand

Concrete command that can be created directly.

Class Type Parameters:

Name Bound or Constraints Description Default
TContext

Type of the context data. Defaults to Any for flexibility. Use explicit type parameter for type-safe commands.

Any
Example
# Untyped command (backward compatible)
cmd = Command(my_func, name="test")

# Typed command with context data type
cmd: Command[MyContext] = Command(
    my_func,
    name="test",
)
Source code in src/slashed/base.py
class Command[TContext = Any](BaseCommand):
    """Concrete command that can be created directly.

    Type Parameters:
        TContext: Type of the context data. Defaults to Any for flexibility.
                  Use explicit type parameter for type-safe commands.

    Example:
        ```python
        # Untyped command (backward compatible)
        cmd = Command(my_func, name="test")

        # Typed command with context data type
        cmd: Command[MyContext] = Command(
            my_func,
            name="test",
        )
        ```
    """

    _execute_func: CommandFunc
    _visible: VisibilityPredicate[TContext] | None

    def __init__(
        self,
        execute_func: CommandFunc,
        *,
        name: str | None = None,
        description: str | None = None,
        category: str = "general",
        usage: str | None = None,
        help_text: str | None = None,
        completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
        condition: ConditionPredicate | None = None,
        visible: VisibilityPredicate[TContext] | None = None,
    ) -> None:
        """Initialize command.

        Args:
            execute_func: Function to execute command
            name: Optional command name (defaults to function name)
            description: Command description (defaults to function docstring)
            category: Command category
            usage: Optional usage string (auto-generated if None)
            help_text: Optional help text (defaults to description)
            completer: Optional completion provider or factory
            condition: Optional predicate to check command availability
            visible: Optional predicate to check command visibility in listings
        """
        self.name = name or getattr(execute_func, "__name__", "unknown").replace("_", "-")
        self.description = description or execute_func.__doc__ or "No description"
        self.category = category
        self.usage = usage or _generate_usage(execute_func)
        self._help_text = help_text or self.description
        self._execute_func = execute_func
        self._completer = completer
        self._condition = condition
        self._visible = visible

    def get_callable(self) -> Callable[..., Any]:
        """The wrapped function, whose signature defines the parameters."""
        return self._execute_func

    def is_available(self) -> bool:
        """Check if command is available based on condition."""
        if self._condition is not None:
            return self._condition()
        return True

    def is_visible(self, ctx: CommandContext[TContext]) -> bool:
        """Check if command should be visible based on visibility predicate."""
        if self._visible is not None:
            return self._visible(ctx)
        return True

    async def execute(
        self,
        ctx: CommandContext[TContext],
        args: list[str] | None = None,
        kwargs: dict[str, str] | None = None,
    ) -> Any:
        """Execute the command using provided function."""
        args = args or []
        kwargs = kwargs or {}

        call_args, coerced_kwargs = parse_args(self._execute_func, ctx, args, kwargs)
        result = self._execute_func(*call_args, **coerced_kwargs)

        if inspect.isawaitable(result):
            return await result
        return result

    @classmethod
    def from_raw(
        cls,
        func: Callable[[CommandContext[Any], list[str], dict[str, str]], Any | Awaitable[Any]],
        *,
        name: str | None = None,
        description: str | None = None,
        category: str = "general",
        usage: str | None = None,
        help_text: str | None = None,
        completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
        condition: ConditionPredicate | None = None,
        visible: VisibilityPredicate[Any] | None = None,
    ) -> Command[Any]:
        """Create a command from a raw-style function.

        Use this for functions that expect the traditional (ctx, args, kwargs) signature,
        such as when wrapping external command sources.

        Args:
            func: Function with signature (ctx, args: list[str], kwargs: dict[str, str])
            name: Optional command name (defaults to function name)
            description: Command description (defaults to function docstring)
            category: Command category
            usage: Optional usage string
            help_text: Optional help text
            completer: Optional completion provider or factory
            condition: Optional predicate to check command availability
            visible: Optional predicate to check command visibility

        Example:
            ```python
            async def handle_external(ctx, args, kwargs):
                await external_system.execute(args, kwargs)

            cmd = Command.from_raw(handle_external, name="external")
            ```
        """

        # Simple wrapper - execute() handles awaitable detection
        def wrapper(ctx: CommandContext[Any], *args: str, **kwargs: str) -> Any:
            return func(ctx, list(args), kwargs)

        # Preserve metadata for name/description inference
        wrapper.__name__ = getattr(func, "__name__", "unknown")
        wrapper.__doc__ = func.__doc__

        return cls(
            wrapper,
            name=name,
            description=description,
            category=category,
            usage=usage,
            help_text=help_text,
            completer=completer,
            condition=condition,
            visible=visible,
        )

    def get_completer(self) -> CompletionProvider | None:
        """Get completion provider."""
        match self._completer:
            case None:
                return None
            case CompletionProvider() as completer:
                return completer
            case Callable() as factory:
                return factory()
            case _:
                typ = type(self._completer)
                msg = f"Completer must be CompletionProvider or callable, not {typ}"
                raise TypeError(msg)

__init__

__init__(
    execute_func: CommandFunc,
    *,
    name: str | None = None,
    description: str | None = None,
    category: str = "general",
    usage: str | None = None,
    help_text: str | None = None,
    completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
    condition: ConditionPredicate | None = None,
    visible: VisibilityPredicate[TContext] | None = None,
) -> None

Initialize command.

Parameters:

Name Type Description Default
execute_func CommandFunc

Function to execute command

required
name str | None

Optional command name (defaults to function name)

None
description str | None

Command description (defaults to function docstring)

None
category str

Command category

'general'
usage str | None

Optional usage string (auto-generated if None)

None
help_text str | None

Optional help text (defaults to description)

None
completer CompletionProvider | Callable[[], CompletionProvider] | None

Optional completion provider or factory

None
condition ConditionPredicate | None

Optional predicate to check command availability

None
visible VisibilityPredicate[TContext] | None

Optional predicate to check command visibility in listings

None
Source code in src/slashed/base.py
def __init__(
    self,
    execute_func: CommandFunc,
    *,
    name: str | None = None,
    description: str | None = None,
    category: str = "general",
    usage: str | None = None,
    help_text: str | None = None,
    completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
    condition: ConditionPredicate | None = None,
    visible: VisibilityPredicate[TContext] | None = None,
) -> None:
    """Initialize command.

    Args:
        execute_func: Function to execute command
        name: Optional command name (defaults to function name)
        description: Command description (defaults to function docstring)
        category: Command category
        usage: Optional usage string (auto-generated if None)
        help_text: Optional help text (defaults to description)
        completer: Optional completion provider or factory
        condition: Optional predicate to check command availability
        visible: Optional predicate to check command visibility in listings
    """
    self.name = name or getattr(execute_func, "__name__", "unknown").replace("_", "-")
    self.description = description or execute_func.__doc__ or "No description"
    self.category = category
    self.usage = usage or _generate_usage(execute_func)
    self._help_text = help_text or self.description
    self._execute_func = execute_func
    self._completer = completer
    self._condition = condition
    self._visible = visible

execute async

execute(
    ctx: CommandContext[TContext],
    args: list[str] | None = None,
    kwargs: dict[str, str] | None = None,
) -> Any

Execute the command using provided function.

Source code in src/slashed/base.py
async def execute(
    self,
    ctx: CommandContext[TContext],
    args: list[str] | None = None,
    kwargs: dict[str, str] | None = None,
) -> Any:
    """Execute the command using provided function."""
    args = args or []
    kwargs = kwargs or {}

    call_args, coerced_kwargs = parse_args(self._execute_func, ctx, args, kwargs)
    result = self._execute_func(*call_args, **coerced_kwargs)

    if inspect.isawaitable(result):
        return await result
    return result

from_raw classmethod

from_raw(
    func: Callable[[CommandContext[Any], list[str], dict[str, str]], Any | Awaitable[Any]],
    *,
    name: str | None = None,
    description: str | None = None,
    category: str = "general",
    usage: str | None = None,
    help_text: str | None = None,
    completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
    condition: ConditionPredicate | None = None,
    visible: VisibilityPredicate[Any] | None = None,
) -> Command[Any]

Create a command from a raw-style function.

Use this for functions that expect the traditional (ctx, args, kwargs) signature, such as when wrapping external command sources.

Parameters:

Name Type Description Default
func Callable[[CommandContext[Any], list[str], dict[str, str]], Any | Awaitable[Any]]

Function with signature (ctx, args: list[str], kwargs: dict[str, str])

required
name str | None

Optional command name (defaults to function name)

None
description str | None

Command description (defaults to function docstring)

None
category str

Command category

'general'
usage str | None

Optional usage string

None
help_text str | None

Optional help text

None
completer CompletionProvider | Callable[[], CompletionProvider] | None

Optional completion provider or factory

None
condition ConditionPredicate | None

Optional predicate to check command availability

None
visible VisibilityPredicate[Any] | None

Optional predicate to check command visibility

None
Example
async def handle_external(ctx, args, kwargs):
    await external_system.execute(args, kwargs)

cmd = Command.from_raw(handle_external, name="external")
Source code in src/slashed/base.py
@classmethod
def from_raw(
    cls,
    func: Callable[[CommandContext[Any], list[str], dict[str, str]], Any | Awaitable[Any]],
    *,
    name: str | None = None,
    description: str | None = None,
    category: str = "general",
    usage: str | None = None,
    help_text: str | None = None,
    completer: CompletionProvider | Callable[[], CompletionProvider] | None = None,
    condition: ConditionPredicate | None = None,
    visible: VisibilityPredicate[Any] | None = None,
) -> Command[Any]:
    """Create a command from a raw-style function.

    Use this for functions that expect the traditional (ctx, args, kwargs) signature,
    such as when wrapping external command sources.

    Args:
        func: Function with signature (ctx, args: list[str], kwargs: dict[str, str])
        name: Optional command name (defaults to function name)
        description: Command description (defaults to function docstring)
        category: Command category
        usage: Optional usage string
        help_text: Optional help text
        completer: Optional completion provider or factory
        condition: Optional predicate to check command availability
        visible: Optional predicate to check command visibility

    Example:
        ```python
        async def handle_external(ctx, args, kwargs):
            await external_system.execute(args, kwargs)

        cmd = Command.from_raw(handle_external, name="external")
        ```
    """

    # Simple wrapper - execute() handles awaitable detection
    def wrapper(ctx: CommandContext[Any], *args: str, **kwargs: str) -> Any:
        return func(ctx, list(args), kwargs)

    # Preserve metadata for name/description inference
    wrapper.__name__ = getattr(func, "__name__", "unknown")
    wrapper.__doc__ = func.__doc__

    return cls(
        wrapper,
        name=name,
        description=description,
        category=category,
        usage=usage,
        help_text=help_text,
        completer=completer,
        condition=condition,
        visible=visible,
    )

get_callable

get_callable() -> Callable[..., Any]

The wrapped function, whose signature defines the parameters.

Source code in src/slashed/base.py
def get_callable(self) -> Callable[..., Any]:
    """The wrapped function, whose signature defines the parameters."""
    return self._execute_func

get_completer

get_completer() -> CompletionProvider | None

Get completion provider.

Source code in src/slashed/base.py
def get_completer(self) -> CompletionProvider | None:
    """Get completion provider."""
    match self._completer:
        case None:
            return None
        case CompletionProvider() as completer:
            return completer
        case Callable() as factory:
            return factory()
        case _:
            typ = type(self._completer)
            msg = f"Completer must be CompletionProvider or callable, not {typ}"
            raise TypeError(msg)

is_available

is_available() -> bool

Check if command is available based on condition.

Source code in src/slashed/base.py
def is_available(self) -> bool:
    """Check if command is available based on condition."""
    if self._condition is not None:
        return self._condition()
    return True

is_visible

is_visible(ctx: CommandContext[TContext]) -> bool

Check if command should be visible based on visibility predicate.

Source code in src/slashed/base.py
def is_visible(self, ctx: CommandContext[TContext]) -> bool:
    """Check if command should be visible based on visibility predicate."""
    if self._visible is not None:
        return self._visible(ctx)
    return True

:fa-brands-github: Show source on GitHub