Typing stubs for click - a command line interface creation kit for Python
Context objects that maintain state and configuration throughout command execution, enabling communication between commands and providing access to execution metadata.
Core context object that maintains execution state and provides command coordination.
class Context:
parent: Context | None
command: Command
info_name: str | None
params: dict[Any, Any]
args: list[str]
protected_args: list[str]
obj: Any
default_map: Mapping[str, Any] | None
invoked_subcommand: str | None
terminal_width: int | None
max_content_width: int | None
allow_extra_args: bool
allow_interspersed_args: bool
ignore_unknown_options: bool
help_option_names: list[str]
token_normalize_func: Callable[[str], str] | None
resilient_parsing: bool
auto_envvar_prefix: str | None
color: bool | None
def __init__(
self,
command: Command,
parent: Context | None = None,
info_name: str | None = None,
obj: Any | None = None,
auto_envvar_prefix: str | None = None,
default_map: Mapping[str, Any] | None = None,
terminal_width: int | None = None,
max_content_width: int | None = None,
resilient_parsing: bool = False,
allow_extra_args: bool | None = None,
allow_interspersed_args: bool | None = None,
ignore_unknown_options: bool | None = None,
help_option_names: list[str] | None = None,
token_normalize_func: Callable[[str], str] | None = None,
color: bool | None = None,
) -> None:
"""
Context for command execution state.
Parameters:
- command: Command being executed
- parent: Parent context for nested commands
- info_name: Command name for help/error messages
- obj: User object for passing data between commands
- auto_envvar_prefix: Prefix for automatic environment variables
- default_map: Default values mapping
- terminal_width: Terminal width for formatting
- max_content_width: Maximum content width
- resilient_parsing: Continue parsing despite errors
- allow_extra_args: Allow extra command arguments
- allow_interspersed_args: Allow interspersed arguments
- ignore_unknown_options: Ignore unknown options
- help_option_names: Names for help options
- token_normalize_func: Function to normalize option names
- color: Enable/disable colored output
"""
@property
def meta(self) -> dict[str, Any]:
"""
Dictionary for storing arbitrary metadata.
Returns:
Metadata dictionary
"""
@property
def command_path(self) -> str:
"""
Full command path from root to current command.
Returns:
Command path string
"""
def fail(self, message: str) -> NoReturn:
"""
Fail with an error message and exit.
Parameters:
- message: Error message
Usage:
if not os.path.exists(filename):
ctx.fail(f'File {filename} does not exist')
"""
def scope(self, cleanup: bool = True) -> ContextManager[Context]:
"""
Create a context manager that provides a new scope.
Parameters:
- cleanup: Whether to cleanup on exit
Returns:
Context manager for scoped execution
Usage:
with ctx.scope() as scope_ctx:
# Work in scoped context
scope_ctx.obj = some_data
"""
def make_formatter(self) -> HelpFormatter:
"""
Create a help formatter for this context.
Returns:
HelpFormatter instance
"""
def call_on_close(self, f: Callable[[], Any]) -> Callable[[], Any]:
"""
Register function to call when context closes.
Parameters:
- f: Function to call on close
Returns:
The registered function
Usage:
def cleanup():
# Cleanup resources
pass
ctx.call_on_close(cleanup)
"""
def close(self) -> None:
"""
Close the context and run cleanup callbacks.
Usage:
ctx.close() # Usually called automatically
"""
def abort(self) -> NoReturn:
"""
Abort command execution immediately.
Usage:
if not confirm_dangerous_operation():
ctx.abort()
"""
def exit(self, code: int | str = 0) -> NoReturn:
"""
Exit with specified code.
Parameters:
- code: Exit code (integer or string)
Usage:
if success:
ctx.exit(0)
else:
ctx.exit(1)
"""
def invoke(self, callback: Command | Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""
Invoke another command or callback with current context.
Parameters:
- callback: Command or function to invoke
- *args: Positional arguments
- **kwargs: Keyword arguments
Returns:
Callback return value
Usage:
# Invoke another command
result = ctx.invoke(other_command, arg1='value')
# Invoke function with context
result = ctx.invoke(my_function, ctx, param1='value')
"""
def forward(self, callback: Command | Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""
Forward to another command, replacing current context.
Parameters:
- callback: Command or function to forward to
- *args: Positional arguments
- **kwargs: Keyword arguments
Returns:
Callback return value
"""
def find_root(self) -> Context:
"""
Find the root context in the hierarchy.
Returns:
Root context
"""
def find_object(self, object_type: type) -> Any:
"""
Find object of specific type in context hierarchy.
Parameters:
- object_type: Type to search for
Returns:
Found object or None
"""
def ensure_object(self, object_type: type) -> Any:
"""
Ensure object of specific type exists in context.
Parameters:
- object_type: Type to ensure
Returns:
Found or created object
"""
def lookup_default(self, name: str) -> Any:
"""
Look up default value for parameter.
Parameters:
- name: Parameter name
Returns:
Default value or None
"""
def get_usage(self) -> str:
"""
Get usage information for current command.
Returns:
Usage string
"""
def get_help(self) -> str:
"""
Get help information for current command.
Returns:
Help string
"""Decorators for accessing context and context objects in command functions.
def pass_context(f: Callable) -> Callable:
"""
Decorator that passes the current context as first argument.
Parameters:
- f: Function to decorate
Returns:
Decorated function
Usage:
@click.command()
@click.pass_context
def my_command(ctx, other_args):
click.echo(f'Command path: {ctx.command_path}')
if ctx.parent:
click.echo('Has parent context')
"""
def pass_obj(f: Callable) -> Callable:
"""
Decorator that passes the context object as first argument.
Parameters:
- f: Function to decorate
Returns:
Decorated function
Usage:
@click.command()
@click.pass_obj
def my_command(obj, other_args):
click.echo(f'Object: {obj}')
"""
def make_pass_decorator(object_type: type, ensure: bool = False) -> Callable:
"""
Create a custom pass decorator for specific object types.
Parameters:
- object_type: Type of object to pass
- ensure: Create object if it doesn't exist
Returns:
Pass decorator function
Usage:
class Config:
def __init__(self):
self.debug = False
pass_config = click.make_pass_decorator(Config, ensure=True)
@click.command()
@pass_config
def debug_command(config):
config.debug = True
"""Functions for managing the global context stack.
def get_current_context(silent: bool = False) -> Context:
"""
Get the current execution context.
Parameters:
- silent: Return None instead of raising if no context
Returns:
Current context
Raises:
RuntimeError: If no context and not silent
Usage:
def helper_function():
ctx = click.get_current_context()
ctx.fail('Something went wrong')
"""
def push_context(ctx: Context) -> None:
"""
Push a context onto the stack.
Parameters:
- ctx: Context to push
Usage:
# Rarely used directly - handled by click framework
click.push_context(new_context)
"""
def pop_context() -> None:
"""
Pop the current context from the stack.
Usage:
# Rarely used directly - handled by click framework
click.pop_context()
"""Utility functions for context management.
def resolve_color_default(color: bool | None = None) -> bool | None:
"""
Resolve color default based on context and environment.
Parameters:
- color: Explicit color setting
Returns:
Resolved color setting
Usage:
# Used internally by click for color handling
color_enabled = click.resolve_color_default(color)
"""Sharing Data Between Commands:
@click.group()
@click.option('--config', type=click.Path(exists=True))
@click.pass_context
def cli(ctx, config):
"""Main CLI with shared configuration."""
ctx.ensure_object(dict)
if config:
with open(config) as f:
ctx.obj = json.load(f)
else:
ctx.obj = {}
@cli.command()
@click.pass_obj
def status(config):
"""Show status using shared config."""
debug = config.get('debug', False)
if debug:
click.echo('Debug mode enabled')
click.echo('Status: OK')Custom Context Objects:
class AppContext:
def __init__(self):
self.debug = False
self.database_url = None
def get_db_connection(self):
# Database connection logic
pass
pass_app_context = click.make_pass_decorator(AppContext, ensure=True)
@click.group()
@click.option('--debug', is_flag=True)
@pass_app_context
def cli(app_ctx, debug):
app_ctx.debug = debug
@cli.command()
@pass_app_context
def migrate(app_ctx):
db = app_ctx.get_db_connection()
if app_ctx.debug:
click.echo('Running migrations in debug mode')Error Handling with Context:
@click.command()
@click.argument('filename')
@click.pass_context
def process_file(ctx, filename):
if not os.path.exists(filename):
ctx.fail(f'File {filename} does not exist')
try:
# Process file
with open(filename) as f:
data = f.read()
except PermissionError:
ctx.fail(f'Permission denied: {filename}')
except Exception as e:
ctx.fail(f'Error processing file: {e}')Internal utility functions for context and parameter processing.
def invoke_param_callback(
callback: Callable[[Context, Parameter, str | None], Any],
ctx: Context,
param: Parameter,
value: str | None,
) -> Any:
"""
Invoke a parameter callback function safely.
Parameters:
- callback: Parameter callback function
- ctx: Current context
- param: Parameter being processed
- value: Parameter value
Returns:
Result of callback invocation
Usage:
# Internal use - rarely needed in user code
result = click.invoke_param_callback(my_callback, ctx, param, value)
"""
def augment_usage_errors(
ctx: Context,
param: Parameter | None = None
) -> ContextManager[None]:
"""
Context manager to enhance usage error messages.
Parameters:
- ctx: Current context
- param: Parameter that caused the error (optional)
Usage:
# Internal use - enhances error reporting
with click.augment_usage_errors(ctx, param):
# Parameter processing that might fail
process_parameter_value()
"""
def iter_params_for_processing(
invocation_order: Sequence[Parameter],
declaration_order: Iterable[Parameter],
) -> Iterable[Parameter]:
"""
Iterate parameters in proper processing order.
Parameters:
- invocation_order: Order parameters were invoked
- declaration_order: Order parameters were declared
Yields:
Parameters in processing order
Usage:
# Internal use - parameter processing order
for param in click.iter_params_for_processing(invoked, declared):
process_parameter(param)
"""Install with Tessl CLI
npx tessl i tessl/pypi-types-click