Slash commands and autocompletions
Project description
Slashed
A Python library for implementing slash commands with rich autocompletion support.
Features
- Simple command registration system
- Rich autocompletion support with multiple providers
- Built-in completers for:
- File paths
- Environment variables
- Choice lists
- Keyword arguments
- Multi-value inputs
- Extensible completion provider system
- Type-safe with comprehensive type hints
- Modern Python features (3.12+)
- Built-in help system
Installation
pip install slashed
Quick Example
from slashed import SlashedCommand, CommandStore, CommandContext
from slashed.completers import ChoiceCompleter
# Define a command with explicit parameters
class GreetCommand(SlashedCommand):
"""Greet someone with a custom greeting."""
name = "greet"
category = "demo"
async def execute_command(
self,
ctx: CommandContext,
name: str = "World",
greeting: str = "Hello",
) -> None:
"""Greet someone.
Args:
ctx: Command context
name: Who to greet
greeting: Custom greeting to use
"""
await ctx.output.print(f"{greeting}, {name}!")
def get_completer(self) -> ChoiceCompleter:
"""Provide name suggestions."""
return ChoiceCompleter({
"World": "Default greeting target",
"Everyone": "Greet all users",
"Team": "Greet the team"
})
# Create store and register the command
store = CommandStore()
store.register_command(GreetCommand)
# Create context and execute a command
ctx = store.create_context(data=None)
await store.execute_command("greet Phil --greeting Hi", ctx)
Command Definition Styles
Slashed offers two different styles for defining commands, each with its own advantages:
Traditional Style (using Command class)
from slashed import Command, CommandContext
async def add_worker(ctx: CommandContext, args: list[str], kwargs: dict[str, str]) -> None:
"""Add a worker to the pool."""
worker_id = args[0]
host = kwargs.get("host", "localhost")
port = kwargs.get("port", "8080")
await ctx.output.print(f"Adding worker {worker_id} at {host}:{port}")
cmd = Command(
name="add-worker",
description="Add a worker to the pool",
execute_func=add_worker,
usage="<worker_id> --host <host> --port <port>",
category="workers",
)
Advantages:
- Quick to create without inheritance
- All configuration in one place
- Easier to create commands dynamically
- More flexible for simple commands
- Familiar to users of other command frameworks
Declarative Style (using SlashedCommand)
from slashed import SlashedCommand, CommandContext
class AddWorkerCommand(SlashedCommand):
"""Add a worker to the pool."""
name = "add-worker"
category = "workers"
async def execute_command(
self,
ctx: CommandContext,
worker_id: str, # required parameter
host: str = "localhost", # optional with default
port: int = 8080, # optional with default
) -> None:
"""Add a new worker to the pool.
Args:
ctx: Command context
worker_id: Unique worker identifier
host: Worker hostname
port: Worker port number
"""
await ctx.output.print(f"Adding worker {worker_id} at {host}:{port}")
Advantages:
- Type-safe parameter handling
- Automatic usage generation from parameters
- Help text generated from docstrings
- Better IDE support with explicit parameters
- More maintainable for complex commands
- Validates required parameters automatically
- Natural Python class structure
- Parameters are self-documenting
When to Use Which?
Use the traditional style when:
- Creating simple commands with few parameters
- Generating commands dynamically
- Wanting to avoid class boilerplate
- Need maximum flexibility
Use the declarative style when:
- Building complex commands with many parameters
- Need type safety and parameter validation
- Want IDE support for parameters
- Documentation is important
- Working in a larger codebase
Generic Context Example
from dataclasses import dataclass
from slashed import Command, CommandStore, CommandContext
# Define your custom context data
@dataclass
class AppContext:
user_name: str
is_admin: bool
# Command that uses the typed context
async def admin_cmd(
ctx: CommandContext[AppContext],
args: list[str],
kwargs: dict[str, str],
) -> None:
if not ctx.data.is_admin:
await ctx.output.print("Sorry, admin access required!")
return
await ctx.output.print(f"Welcome admin {ctx.data.user_name}!")
# Create and register the command
admin_command = Command(
name="admin",
description="Admin-only command",
execute_func=admin_cmd,
category="admin",
)
# Setup the store with typed context
store = CommandStore()
store.register_command(admin_command)
# Create context with your custom data
ctx = store.create_context(
data=AppContext(user_name="Alice", is_admin=True)
)
# Execute command with typed context
await store.execute_command("admin", ctx)
Documentation
For full documentation including advanced usage and API reference, visit slashed.readthedocs.io.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. Make sure to read our contributing guidelines first.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file slashed-0.3.0.tar.gz.
File metadata
- Download URL: slashed-0.3.0.tar.gz
- Upload date:
- Size: 22.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.0.1 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3a2e5bd1f87a7991755a48da44640adabc1cdacb59e88dc35071f3283c18af9d
|
|
| MD5 |
32ebadd3b2f6f0599814e0aa739b9f7c
|
|
| BLAKE2b-256 |
a3ccab2a50f4183805cd38c72bc8e35038f070145ed8b596d518dedfe0a579a4
|
Provenance
The following attestation bundles were made for slashed-0.3.0.tar.gz:
Publisher:
build.yml on phil65/slashed
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
slashed-0.3.0.tar.gz -
Subject digest:
3a2e5bd1f87a7991755a48da44640adabc1cdacb59e88dc35071f3283c18af9d - Sigstore transparency entry: 157945410
- Sigstore integration time:
-
Permalink:
phil65/slashed@8f768722ab6c2087ca2dcfb64141fcf82ef32b0d -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/phil65
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build.yml@8f768722ab6c2087ca2dcfb64141fcf82ef32b0d -
Trigger Event:
push
-
Statement type:
File details
Details for the file slashed-0.3.0-py3-none-any.whl.
File metadata
- Download URL: slashed-0.3.0-py3-none-any.whl
- Upload date:
- Size: 19.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.0.1 CPython/3.12.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e6c98d46694331f1ebb7b36ee746789a0dea75c2a673ebecc7d5ba06296a917f
|
|
| MD5 |
81ae79ad12ccd3235b09e67a677325fa
|
|
| BLAKE2b-256 |
dfa0cd2ad3954430c19d89ab7f1967e190696dd4fff2825601011b4cb8593f4c
|
Provenance
The following attestation bundles were made for slashed-0.3.0-py3-none-any.whl:
Publisher:
build.yml on phil65/slashed
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
slashed-0.3.0-py3-none-any.whl -
Subject digest:
e6c98d46694331f1ebb7b36ee746789a0dea75c2a673ebecc7d5ba06296a917f - Sigstore transparency entry: 157945411
- Sigstore integration time:
-
Permalink:
phil65/slashed@8f768722ab6c2087ca2dcfb64141fcf82ef32b0d -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/phil65
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
build.yml@8f768722ab6c2087ca2dcfb64141fcf82ef32b0d -
Trigger Event:
push
-
Statement type: