API Reference#

Auto-Completion#

Configuration and Utilities for auto-completion in the REPL.

class click_repl.completer.ClickCompleter(group_ctx: Context, internal_commands_system: InternalCommandSystem, bottom_bar: AnyFormattedText | BottomBar = None, shortest_option_names_only: bool = False, show_only_unused_options: bool = False, show_hidden_commands: bool = False, show_hidden_params: bool = False)[source]#

Custom prompt completion provider for the click-repl app.

Parameters:
  • group_ctx – The click context object of the main group.

  • bottom_bar – Object that’s used to update the text displayed in the bottom bar. If not required, it should be explicitly set to None.

  • internal_commands_system – Object that holds the information about the internal commands and their prefixes.

  • shortest_option_names_only

    Determines whether only the shortest name of an option parameter should be used for auto-completion.

    It is utilized when the user is requesting option flags without providing any text. They are not considered for option flags.

  • show_only_unused_options – Determines whether the options that are already mentioned or used in the current prompt will be displayed during auto-completion.

  • show_hidden_commands – Determines whether hidden commands should be shown in auto-completion or not.

  • show_hidden_params – Determines whether hidden parameters should be shown in auto-completion or not.

check_for_command_arguments_request(ctx: Context, state: ReplInputState, incomplete: Incomplete) bool[source]#

Determines whether the user has requested auto-completions for the given command’s parameters.

Parameters:
  • ctx – The current click context object.

  • state – Object that contains information about the input state of the parameters of the current command.

  • incomplete – Object that contains the unfinished string in the REPL prompt, and its parsed state, that requires further input or completion.

Returns:

boolTrue if auto-completions should be generated for the parameters of the given command, False otherwise.

get_completion_for_boolean_type(param: Parameter, incomplete: Incomplete) Generator[Completion, None, None][source]#

Generates auto-completions for BOOL type parameter based on the given param.

Parameters:
  • param – The parameter for which auto-completions are generated.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing boolean types.

get_completion_for_command_arguments(ctx: Context, command: Command, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#

Generates auto-completions to display the flags of the options based on the given command object.

Parameters:
  • ctx – The current click context object.

  • command – A click command object for which auto-completions are generated based on its parameters.

  • state – Object that contains information about the input state of the parameters of the current command.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing the current command’s arguments.

get_completion_for_option_flags(ctx: Context, command: Command, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#

Generates auto-completions for option flags based on the given command.

Parameters:
  • ctx – The current click context object.

  • command – A click command object, which is referred to generate auto-completions based on its parameters.

  • state – Object that contains information about the input state of the parameters of the current command.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing the given flag-type option.

get_completion_for_path_types(param: Parameter, param_type: click.Path | click.File, incomplete: Incomplete) Generator[Completion, None, None][source]#

Generates auto-completions for Path and File type parameters.

Parameters:
  • param – The parameter for which auto-completions are generated.

  • param_type – The Path or File ParamType object of the param.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing click path types.

get_completion_from_autocompletion_functions(ctx: Context, param: Parameter, state: ReplInputState, incomplete: Incomplete, param_type: ParamType | None = None) Generator[Completion, None, None][source]#

Generates auto-completions based on the output from the command’s shell_complete() or autocompletion function of the param.

Parameters:
  • ctx – The current click context object.

  • param – The parameter for which auto-completions are generated.

  • state – Object that contains information about the input state of the current parameter.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

  • param_type – The ParamType object of a parameter, to which the auto-completions are generated from their shell_complete() methods.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completion for the given parameter and/or its type.

get_completion_from_choices_type(param: Parameter, param_type: click.Choice, incomplete: Incomplete) Generator[Completion, None, None][source]#

Generates auto-completions based on data from the given Choice parameter type of a param.

This method is used for backwards compatibility with click v7 as Choice class didn’t have a shell_complete() method until click v8.

Parameters:
  • param – The parameter for which auto-completions are generated.

  • param_type – The Choice ParamType object of param, to which the auto-completions are generated.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completions for the choices type.

get_completion_from_param(ctx: Context, param: Parameter, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#

Generates auto-completions based on the given param.

Parameters:
  • ctx – The current click context object.

  • param – The parameter for which auto-completions are generated.

  • state – Object that contains information about the input state of the parameters of the current command.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing the given parameter.

get_completion_from_param_type(ctx: Context, param: Parameter, param_type: ParamType, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#

Generates auto-completions based on the given param_type object of the given param.

Parameters:
  • ctx – The current click context object.

  • param – The parameter for which auto-completions are generated.

  • param_type – The ParamType object of param, defining the type of value to be generated.

  • state – Object that contains information about the input state of the parameters of the current command.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing the ParamType of the current parameter.

get_completions(document: Document, complete_event: CompleteEvent | None = None) Generator[Completion, None, None][source]#

Provides Completion objects from the obtained current input string in the REPL prompt.

Parameters:
  • document – The Document object containing the text that’s currently in the REPL.

  • complete_event – The CompleteEvent object of the current prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for command line auto-completion.

get_completions_for_internal_commands(prefix: str, incomplete: str) Generator[Completion, None, None][source]#

Generates auto-completions based on the given prefix present in the current incomplete prompt.

Parameters:
  • prefix – The prefix string thats present in the start of the prompt.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing internal commands.

get_completions_for_joined_boolean_option_flags(ctx: Context, option: click.Option, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#

Generates auto-completions for boolean option flags, to display all their names joined together in a single command-line sugestion, if shortest_option_names_only is set to True.

It also generates coloured option flags, only if there are any exclusive flags to pass in the “False’y” value of the specified option.

Parameters:
  • ctx – The current click context object.

  • option – A click option object which is referred to generate auto-completions for its flags

  • state – Object that contains information about the input state of the parameters of the current command.

  • incomplete – Object that contains the unfinished string in the REPL prompt

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing the given boolean flag option.

get_completions_for_subcommands(ctx: Context, state: ReplInputState, incomplete: Incomplete) Generator[Completion, None, None][source]#

Provides auto-completions for command names, based on the current command and group.

Parameters:
  • ctx – The current click context object.

  • state – Object that contains information about the input state of the parameters of the current command.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

prompt_toolkit.completion.Completion – Completion objects to auto-complete sub-command names of the current group.

get_multicommand_for_generating_subcommand_completions(ctx: Context, state: ReplInputState, incomplete: Incomplete) MultiCommand | None[source]#

Returns the appropriate MultiCommand object that should be used to generate auto-completions for suggesting subcommands of a group.

Parameters:
  • ctx – The current click context object.

  • state – Object that contains information about the input state of the parameters of the current command.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Returns:

MultiCommand | None – A click multiCommand object, if available, which is supposed to be used for generating auto-completion for suggesting its subcommands.

get_visible_subcommands(ctx: Context, multicommand: MultiCommand, incomplete: str) Generator[Command, None, None][source]#

Get all the subcommands from the given multicommand whose name starts with the given incomplete prefix string.

Parameters:
  • ctx – The current click context object.

  • multicommand – A click multicommand object, which is used for generating auto-completion for suggesting its subcommands.

  • incomplete – Object that contains the incomplete string in the REPL prompt.

Yields:

click.Command – Click command type sub-command objects of the multicommand object.

handle_internal_commands_request(document_text: str) Generator[Completion, None, bool][source]#

Handles internal commands request from the REPL, by suggesting auto-completions for the incomplete internal command request, and clearing the bottom bar, if exists.

Parameters:

document_text – The text currently in the REPL prompt.

Returns:

boolTrue if there’s an internal command request from the REPL, False otherwise.

Yields:

prompt_toolkit.completion.Completion – Completion objects for auto-completing internal commands.

bottom_bar[source]#

Object that’s used to update the text displayed in the bottom bar. If not required, it should be explicitly set to None.

group_ctx: Final[Context][source]#

The click context object of the main group.

internal_commands_system[source]#

Holds information about the internal commands and their prefixes.

parent_token_class_name: str[source]#

Parent class name for tokens that are related to ClickCompleter.

shortest_option_names_only[source]#

Determines whether only the shortest name of an option parameter should be used for auto-completion.

show_hidden_commands[source]#

Determines whether the hidden commands should be shown in auto-completion or not.

show_hidden_params[source]#

Determines whether the hidden parameters should be shown in auto-completion or not.

show_only_unused_options[source]#

Determines whether the options that are already mentioned or used in the current prompt will be displayed during auto-completion.

class click_repl.completer.ReplCompletion(text: str, incomplete: Incomplete | str, *args: Any, **kwargs: Any)[source]#

Custom Completion class for generating Completion objects with the default settings for proper auto-completion in the REPL prompt.

Parameters:
  • text – The string that should fill in the prompt during auto-completion.

  • incomplete – The incomplete string in the prompt. It’s used to get the start_position for the Completion to swap text with.

  • *args – Additional arbitrary arguments for the Completion class.

  • **kwargs – Additional keyword arguments for the Completion class.

Context#

Core functionalities for managing context of the click_repl app.

class click_repl.core.ReplContext(group_ctx: Context, internal_command_system: InternalCommandSystem, bottombar: AnyFormattedText | BottomBar = None, prompt_kwargs: dict[str, Any] = {}, parent: ReplContext | None = None)[source]#

Context object for the REPL sessions.

This class tracks the depth of nested REPLs, ensuring seamless navigation between different levels. It facilitates nested REPL scenarios, allowing multiple levels of interactive REPL sessions.

Each REPL’s properties are stored inside this context class, allowing them to be accessed and shared with their parent REPL.

All the settings for each REPL session persist until the session is terminated.

Parameters:
  • group_ctx – The click context object that belong to the CLI/parent Group.

  • internal_command_system – Holds information about the internal commands and their prefixes.

  • bottom_bar

    Text or callable returning text, that should be displayed in the bottom toolbar of the PromptSession object.

    Alternatively, it can be a BottomBar object to dynamically adjust the command description displayed in the bottom bar based on the user’s current input state.

  • prompt_kwargs – Extra keyword arguments for PromptSession class.

  • parent – REPL Context object of the parent REPL session, if exists. Otherwise, None.

history() Generator[str, None, None][source]#

Generates the history of past executed commands.

Yields:

str – The executed command string from the history, in chronological order from most recent to oldest.

session_reset() None[source]#

Resets values of PromptSession to the provided prompt_kwargs, discarding any changes done to the PromptSession object.

to_info_dict() ReplContextInfoDict[source]#

Provides a dictionary with minimal info about the current REPL.

Returns:

ReplContextInfoDict – A dictionary that has the instance variables and their values.

update_state(state: ReplInputState) None[source]#

Updates the current input state of the REPL in itself, and in bottom_bar.

Parameters:

state – A ReplInputState object that keeps track of the current input state.

bottom_bar[source]#

Text or callable returning text, that should be displayed in the bottom toolbar of the PromptSession object.

Alternatively, it can be a BottomBar object to dynamically adjust the command description displayed in the bottom bar based on the user’s current input state.

current_state: ReplInputState | None[source]#

Current input state of the commands and their parameters in the REPL.

group_ctx: Final[Context][source]#

The click context object that belong to the CLI/parent Group.

internal_command_system[source]#

Holds information about the internal commands and their prefixes.

parent: Final[ReplContext | None][source]#

REPL Context object of the parent REPL session, if exists. Otherwise, None.

property prompt: AnyFormattedText[source]#

The prompt text of the REPL field.

Returns:

prompt_toolkit.formatted_text.AnyFormattedText – The prompt object if isatty() is True, else None.

prompt_kwargs[source]#

Extra keyword arguments for PromptSession class.

session[source]#

Object that’s responsible for managing and executing the REPL.

click_repl.core.pass_context(func: Callable[[Concatenate[ReplContext, P]], R]) Callable[[P], R][source]#

Decorator that marks a callback function to receive the current REPL context object as its first argument.

Parameters:

func – The callback function to pass context as its first parameter.

Returns:

Callable[P,R] – The decorated callback function that receives the current REPL context object as its first argument.

Internal Commmands#

Utilities to manage the REPL’s internal commands.

class click_repl.internal_commands.InternalCommandSystem(internal_command_prefix: str | None = ':', system_command_prefix: str | None = '!')[source]#

Utility for managing and executing internal/system commands from the REPL. Commands are triggered by their respective prefixes.

Parameters:
  • internal_command_prefix – Prefix to trigger internal commands.

  • system_command_prefix – Prefix to execute command-line scripts.

Raises:

click_repl.exceptions.SamePrefix – If both internal_command_prefix and system_command_prefix are same.

Note

The prefixes determine how the commands are recognized and distinguished within the REPL.

Both the internal_command_prefix and system_command_prefix should not be the same.

dispatch_system_commands(command: str) None[source]#

Execute system commands entered in the REPL. System commands start with the system_command_prefix string in the REPL.

Parameters:

command – Contains the system command that needs to be executed.

execute(string: str) None[source]#

Executes incoming Internal and System commands.

Parameters:

string – Input string that has to be parsed and executed.

Raises:

PrefixNotFound – If there is no internal prefix used in the given command.

get_command(name: str, default: ~click_repl.internal_commands.T = <object object>) Callable[[], None] | T[source]#

Retrieves the callback function of the internal command if available.

Parameters:
  • name – The name of the desired internal command.

  • default – The sentinel value that has to be returned if the internal command with the given name is not found.

Returns:

Callable[[],None] | T – The callback function of the internal command, if found. Otherwise, it returns the value specified in the default parameter.

get_prefix(command: str) tuple[str, str | None][source]#

Extracts the prefix from the beginning of the command string.

Parameters:

command – Input string that needs to be parsed.

Returns:

tuple[str,str | None] – A tuple containing: - The type of the prefix. - The prefix found at the beginning of the command string. None if its not known.

handle_internal_commands(command: str) None[source]#

Run REPL-internal commands that start with the internal_command_prefix string in the REPL.

Parameters:

command – Contains the internal command that needs to be to be executed.

list_commands() list[list[str]][source]#

List of internal commands that are available.

Returns:

list[list[str]] – Contains all the names and aliases of each available internal command.

register_command(target: Callable[[], None] | None = None, *, names: str | Sequence[str] | Generator[str, None, None] | Iterator[str] | None = None, description: str | None = None) Callable[[Callable[[], None]], Callable[[], None]] | Callable[[], None][source]#

Decorator used to register a new internal command from the given function.

Internal commands are case-insensitive, and this decorator allows for easy registration of command names and aliases.

Parameters:
  • target – The callback function for the internal command.

  • names – Names and aliases for the internal command.

  • description – Help text for the internal command.

Returns:

Callable[[Callable[[],None]],Callable[[],None]] | Callable[[],None] – The same function object passed into this decorator, or a function that takes and returns the same function when called.

remove_command(name: str, remove_all_aliases: bool = True) None[source]#

Removes the internal command with the given name, if it exists.

Parameters:
  • name – The name of the internal command to be removed.

  • remove_all_aliases – Determines whether to remove all aliases associated with the command.

Raises:

InternalCommandNotFound – If there’s no such internal command with the specific name.

validate_prefix(prefix: str | None, var_name: str) None[source]#

Raises an error if the given prefix is not in the expected format.

Parameters:
  • prefix – The prefix to be checked.

  • var_name – The name of the variable passed to the prefix argument.

Raises:
property internal_command_prefix: str | None[source]#

Prefix to trigger internal commands.

Returns:

str | None – The prefix for internal commands, if available.

Raises:
prefix_table: PrefixTable[source]#

Table to keep track of the prefixes.

property system_command_prefix: str | None[source]#

Prefix to execute system commands.

Returns:

str | None – The prefix for system commands, if available.

Raises:
click_repl.internal_commands.repl_exit() NoReturn[source]#

Exits the REPL.

Validation#

Core utilities for input validation and displaying error messages raised during auto-completion.

class click_repl.validator.ClickValidator(group_ctx: Context, internal_commands_system: InternalCommandSystem, display_all_errors: bool = True)[source]#

Custom prompt input validation for the REPL.

Parameters:
  • group_ctx – The current click context object.

  • internal_commands_system – Holds information about the internal commands and their prefixes.

  • display_all_errors – Determines whether to raise generic python exceptions, and not display them in the validator bar, resulting in the full error traceback being redirected to a log file.

validate(document: Document) None[source]#

Validates the input from the prompt.

Any errors raised while parsing text in prompt are displayed in the validator bar.

Parameters:

document – The incomplete string from the REPL prompt.

Raises:
display_all_errors[source]#

Determines whether to raise generic python exceptions, and not display them in the validator bar.

group_ctx: Final[Context][source]#

The click context object of the main group.

internal_commands_system[source]#

The InternalCommandSystem object of the current REPL session.

Bottom Bar#

Utility for the Bottom bar of the REPL.

class click_repl.bottom_bar.BottomBar(show_hidden_params: bool = False)[source]#

Manage the text displayed in the bottom bar.

Parameters:

show_hidden_params – Determines whether to display hidden params at bottom bar.

clear() None[source]#

Clears the text content of the bottom bar.

display_exception(exc: Exception) None[source]#

Displays the provided exception, which was raised during auto-completion generation, in the bottom bar. The exception appears as text with a red background, replacing the display of the metavar description for the current group or the current command’s arguments.

Parameter#

exc

The exception that should be displayed in the bottom bar.

format_metavar_tokens_for_param_with_nargs(param: Parameter, param_info: ParamInfo) ListOfTokens[source]#

Constructs the final tokens list to describe the given param, incorporating information from the provided param_info dictionary.

Parameters:
  • param – The parameter to be described.

  • param_info – A dictionary that has tokens lists that describe about the given parameter.

Returns:

ListOfTokens – Tokens that describe the given param, including appropriate metavar templates and formatting.

get_formatted_text() ListOfTokens[source]#

Retrieves the next chunk of text to be displayed in the bottom bar, sliced from the text object.

Returns:

ListOfTokens – The next chunk of text to be displayed in bottom bar.

get_group_metavar_template() Marquee[source]#

Gets the metavar to describe the CLI Group, indicating whether it is a Group or a Command.

Returns:

Marquee – A pre-defined set of metavar tokens for both the prefix and text attributes.

get_param_info_tokens(param: Parameter) ListOfTokens[source]#

Constructs the final tokens list to describe the given param. This method constructs the param_info dictionary internally and passes it along to other methods to feed in the description about the param.

Parameters:
  • param – The parameter to be described.

  • param_info – A dictionary that has tokens lists that describe about the given parameter.

Returns:

ListOfTokens – Tokens that describe the given param with appropriate metavar templates and formatting.

get_param_name_token(param: Parameter) Token[source]#

Returns the token representing the name of the given param, based on its type.

Parameters:

param – The click parameter for which to determine its name token.

Returns:

Token – Token that represents the given param’s name.

get_param_nargs_info_tokens(param: Parameter, param_info: ParamInfo) ListOfTokens[source]#

Constructs tokens list to describe the nargs information of the given param.

Parameters:
  • param – The parameter for which its nargs information must be described.

  • param_info – A dictionary that has tokens lists that describe about the given parameter.

Returns:

ListOfTokens – Tokens that describe the nargs information of the given param with proper metavar content.

get_param_tuple_type_info_tokens(param: Parameter) ListOfTokens[source]#

Constructs tokens list to describe the given param’s Tuple type.

Parameters:

param – The click parameter for which its types in Tuple needs to be described.

Returns:

ListOfTokens – Tokens that describe the given param’s type.

get_param_type_info_tokens(param: Parameter, param_type: ParamType) ListOfTokens[source]#

Constructs tokens list to describe the param_type of the given param.

Parameters:
  • param – The parameter for which its type must be described.

  • param_type – The ParamType of the given param. This can be an individual ParamType object from the list in Tuple.

Returns:

ListOfTokens – Tokens that describe the type of the given param, based on the specified param_type.

get_param_usage_state_token(param: Parameter) str[source]#

Returns a token class name that describes the usage state of a parameter in the context of a REPL.

Parameters:

param – The click parameter for which to determine its usage state.

Returns:

str – A string describing the given param’s usage state.

make_formatted_text() Marquee[source]#

Constructs a Marquee object containing tokens to describe the current REPL input state of the prompt.

Returns:

click_repl.tokenizer.Marquee – Marquee object that needs to be displayed to show the updated information about the current REPL input state.

reset_state() None[source]#

Resets the current input state object and clears the content in the bottom bar.

update_state(state: ReplInputState) None[source]#

Updates the current input state object in the BottomBar.

Parameters:

state – Current input state of the prompt.

parent_token_class_name: str[source]#

Parent class name for tokens that are related to BottomBar.

show_hidden_params[source]#

Determines whether to display hidden params at bottom bar

state: ReplInputState | None[source]#

Current REPL input state object.

Repl#

Core functionality of the REPL.

class click_repl._repl.Repl(ctx: Context, prompt_kwargs: dict[str, Any] = {}, completer_cls: type[Completer] = <object object>, validator_cls: type[Validator] | None = <object object>, completer_kwargs: dict[str, Any] = {}, validator_kwargs: dict[str, Any] = {}, internal_command_prefix: str | None = ':', system_command_prefix: str | None = '!')[source]#

Executes the REPL with proper necessary arrangements.

Parameters:
  • ctx – The root/parent/CLI group’s context object.

  • prompt_kwargs – Keyword arguments passed to the PromptSession class.

  • completer_cls – Completer type class to generate ClickCompleter class is used by default.

  • validator_cls – Validator class to display error messages in the validator bar during input validation. ClickValidator class is used by default.

  • completer_kwargs – Keyword arguments passed to the constructor of completer_cls class.

  • validator_kwargs – Keyword arguments passed to the constructor of validator_cls class.

  • internal_command_prefix – Prefix that triggers internal commands within the REPL.

  • system_command_prefix – Prefix that triggers system commands within the REPL.

Note

You don’t have to pass the Completer and Validator objects via prompt_kwargs. But if its still done, then the REPL uses the completer and validator from it.

execute_click_command(command: str | Sequence[str]) None[source]#

Executes click command received from the REPL.

Parameters:

command – The command string to be parsed and executed.

execute_command(command: str) None[source]#

Executes commands received from the REPL.

Parameters:

command – The command string to be parsed and executed.

get_command() str[source]#

Retrieves input for the REPL.

Returns:

str – Input text from REPL prompt.

get_default_completer_kwargs(completer_cls: type[Completer] | None, completer_kwargs: dict[str, Any]) dict[str, Any][source]#

Generates default keyword arguments for initializing a Completer object, either using default values or user-defined values, if available.

Parameters:
  • completer_cls – A completer class.

  • completer_kwargs – Keyword arguments passed to the completer_cls class.

Returns:

dict[str,Any] – Keyword arguments that should be passed to the Completer class.

get_default_prompt_kwargs(completer_cls: type[Completer], completer_kwargs: dict[str, Any], validator_cls: type[Validator] | None, validator_kwargs: dict[str, Any], prompt_kwargs: dict[str, Any], style_config_dict: dict[str, str] = {}) dict[str, Any][source]#

Generates default keyword arguments for initializing a PromptSession object, either using default values or user-defined values, if available.

Parameters:
  • completer_cls – A completer class.

  • completer_kwargs – Keyword arguments passed to the completer_cls class.

  • validator_cls – A validator class.

  • validator_kwargs – Keyword arguments passed to the validator_cls class.

  • prompt_kwargs – Keyword arguments passed to the PromptSession class.

  • style_config_dict – Style configuration for the REPL.

Returns:

dict[str,Any] – Keyword arguments that should be passed to the PromptSession class.

get_default_validator_kwargs(validator_cls: type[Validator] | None, validator_kwargs: dict[str, Any]) dict[str, Any][source]#

Generates default keyword arguments for initializing a Validator object, either using default values or user-defined values, if available.

Parameters:
  • validator_cls – A validator class.

  • validator_kwargs – Keyword arguments passed to the validator_cls class.

Returns:

dict[str,Any] – Keyword arguments that should be passed to the validator_cls class.

loop() None[source]#

Starts the REPL.

bottom_bar: AnyFormattedText | BottomBar[source]#

Text or callable returning text, that should be displayed in the bottom toolbar of the PromptSession object.

Alternatively, it can be a BottomBar object to dynamically adjust the command description displayed in the bottom bar based on the user’s current input state.

group_ctx: Context[source]#

click context of the parent/CLI group the to retrieve its subcommands.

internal_commands_system: InternalCommandSystem[source]#

Handles and executes internal commands that are invoked in repl.

repl_ctx: ReplContext[source]#

Context object for the current REPL session.

class click_repl._repl.ReplGroup(prompt: str = '> ', startup: Callable[[], None] | None = None, cleanup: Callable[[], None] | None = None, repl_kwargs: dict[str, Any] = {}, **attrs: Any)[source]#

Custom Group subclass for initialing the REPL.

This class extends the functionality of the Group class and is designed to be used as a wrapper to automatically invoke the repl() function when the group is invoked without any sub-command.

Parameters:
  • prompt – The prompt text for the REPL.

  • startup – The callback function that gets called before invoking the REPL.

  • cleanup – The callback function that gets invoked after exiting the REPL.

  • repl_kwargs – The keyword arguments that needs to be sent to the repl() function.

  • **attrs – Extra keyword arguments to be passed to the click.Group class.

invoke(ctx: Context) Any[source]#

Given a context, this invokes the attached callback (if it exists) in the right way.

cleanup[source]#

The callback function that gets invoked after exiting the REPL.

prompt[source]#

The prompt text for the REPL.

repl_kwargs[source]#

The keyword arguments that needs to be sent to the repl() function.

startup[source]#

The callback function that gets called before invoking the REPL.

click_repl._repl.register_repl(group: Group | None = None, *, name: str = 'repl', remove_command_before_repl: bool = False) Callable[[Group], Group] | Group[source]#

Decorator that registers repl() as a sub-command named name within the group.

Parameters:
  • group – The parent click group object to which the REPL command will be registered.

  • name – The name of the repl command to be in the given group.

  • remove_command_before_repl – Determines whether to remove the REPL command from the group, before its execution or not.

Returns:

Callable[[Group],Group] | Group – The same group or a callback that returns the same group with the REPL command registered to it.

Raises:

TypeError – If the given group is not an instance of Group.

click_repl._repl.repl(group_ctx: Context, prompt_kwargs: dict[str, Any] = {}, cls: type[Repl] = <class 'click_repl._repl.Repl'>, **attrs: Any) None[source]#

Starts an Interactive Shell where all subcommands are available.

If stdin is not a TTY, no prompt will be printed, but only subcommands can be read from stdin.

Parameters:
  • group_ctx – The current click context object.

  • prompt_kwargs – Parameters that should be passed to PromptSession. These parameters configure the prompt appearance and behavior, such as prompt message, history, completion, etc.

  • cls – Repl class to use for the click_repl app. if None, the Repl class is used by default. This allows customization of the REPL behavior by providing a custom Repl subclass.

  • **attrs – Extra keyword arguments to be passed to the Repl class. These additional arguments can be used to further customize the behavior of the Repl class.

Notes

  • You don’t have to pass the Completer and Validator class, and their arguments via the prompt_kwargs dictionary. Pass them separately in the completer_cls and validator_cls arguments respectively.

  • Provide a text, a function, or a BottomBar object to determine the content that will be displayed in the bottom toolbar via the bottom_toolbar key in the prompt_kwargs dictionary. To disable the bottom toolbar, pass None as the value for this key.

Tokenization#

Utilities to create and manage tokens.

class click_repl.tokenizer.Marquee(text: ListOfTokens, prefix: ListOfTokens = [])[source]#

Displays the given text in the form of a marquee in terminal.

Parameters:
  • text – The text tokens that will be displayed in the marquee style, if the terminal width is insufficient to display the entire text. Otherwise, the entire text is displayed statically.

  • prefix – This text will be displayed as a prefix before text, and stays at the left most end of the bottom bar and remains static.

adjust_pointer_position() None[source]#

Updates the pointer_position for the next iteration, for updating the text from the next offset location.

get_current_text_chunk() TokenizedFormattedText[source]#

Returns the updated text chunk, along with the prefix, that should currently be displayed in the bottom bar.

Returns:

TokenizedFormattedText – The entire text with the prefix if the terminal window length is sufficient. Otherwise, returns a sliced portion of the text that fits the current window size.

get_full_formatted_text() TokenizedFormattedText[source]#

Returns the complete content of text along with the prefix, without slicing them.

Returns:

TokenizedFormattedText – The entire content of both prefix and the text.

get_window_size() int[source]#

Returns the window size to display the text as a marquee.

Returns:

int – New window size to display a chunk of text.

hit_boundary: bool[source]#

Indicates whether the pointer has hit either the left or right-most end.

is_pointer_direction_left: bool[source]#

Keeps track on the current direction on pointer’s movement.

max_wait_in_iterations: int[source]#

Maximum number of iterations the pointer can stay idle once it has hit either of the ends.

no_of_iterations_waited_for: int[source]#

The pointer stays at the very end once it has touched the boundary, for next no_of_iterations_waited_for iterations.

pointer_position: int[source]#

Keeps track of the next starting position to slice the text from.

prefix: TokenizedFormattedText[source]#

Prefix that appear before text, and stays at the left-most end of the bottom bar and remains static.

text: TokenizedFormattedText[source]#

Text that will be displayed in the marquee style, if the terminal width is insufficient to display the entire text. Otherwise, the entire text is displayed statically.

class click_repl.tokenizer.TokenizedFormattedText(tokens_list: ListOfTokens, parent_token_class: str = '')[source]#

Sub-class of FormattedText, but has custom slicing method, based on its display text.

Parameters:
  • tokens_list – List of Token tuples.

  • parent_token_class – Parent class name for the tokens in the given tokens_list.

content_length() int[source]#

Returns the length based on the length of text content in each token.

Returns:

int – Total length of text content in the tokens list.

get_text() str[source]#

Returns the entire display text from each token in a single string.

Returns:

str – Display text altogether from all the tokens.

slice_by_textual_content(start: int, stop: int) TokenizedFormattedText[source]#

Slices the tokens based on the text content in them.

Parameters:
  • start – Starting position to slice tokens.

  • stop – Last position to stop slicing tokens.

Returns:

TokenizedFormattedText – A new slice that contains the text content within that slice range.

parent_token_class: str[source]#

Parent class name for the tokens in the given tokens_list.

Parsing#

Parsing functionalities for the module.

class click_repl.parser.Incomplete(raw_str: str, parsed_str: str)[source]#

Stores the last incomplete text token in the current prompt input, that requires suggestions. It stores the incomplete last text token in its raw form in raw_str attribute, and in its parsed form in parsed_str attribute. The parsed form has no unpaired quotes surrounding it if the draw form had any.

Parameters:
  • raw_str – Raw form of the incomplete text.

  • parsed_str – Parsed form of the raw incomplete text.

expand_envvars() str[source]#

Expands Environmental variables in parsed_str and returns it as a new string.

Returns:

str – String with all the Environmental in parsed_str variables expanded.

parsed_str[source]#

Parsed form of the raw incomplete text.

raw_str[source]#

Raw form of the incomplete text.

class click_repl.parser.ReplInputState(cli_ctx: Context, current_ctx: Context, args: tuple[str, ...])[source]#

Describes about the current input state of the text in the current prompt. It includes the details about the current click group, command and parameter the user is requesting autocompletions for.

Parameters:
  • cli_ctx – The click context object of the main group.

  • current_ctx – The most recently created click context object, after parsing args.

  • args – List of text that’s entered in the prompt.

get_current_arg(current_command: Command) Argument | None[source]#

Parse the current_ctx and returns the current click argument from the given current_command that’s been requested in the prompt.

Parameters:

current_command – The current click command.

Returns:

click.Argument | None – The current click argument, if requested, in the prompt.

get_current_group_and_command() tuple[Group, Command | None][source]#

Parse the current_ctx and returns the current click group and command that’s been requested in the prompt.

Returns:

tuple[Group,Command | None] – The current click group and command, if requested, in the prompt.

get_current_opt(current_command: Command) Option | None[source]#

Parse the current_ctx and returns the current click option from the given current_command that’s been requested in the prompt.

Parameters:

current_command – The current click command.

Returns:

click.Option | None – The current click option, if requested, in the prompt.

get_current_param(current_command: Command) Parameter | None[source]#

Parse the current_ctx and returns the current click parameter from the given current_command that’s been requested in the prompt.

Parameters:

current_command – The current click command.

Returns:

Parameter | None – The current click parameter, if requested, in the prompt.

parse() tuple[Group, Command | None, Parameter | None][source]#

Parse the :attr`~.current_ctx` and returns the current click group, command and paramter that’s been requested in the prompt.

Returns:

tuple[Group,Command | None,Parameter | None] – The current click group, command and parameter, if requested, in the prompt.

args[source]#

List of text that’s entered into the prompt.

cli_ctx[source]#

The click context object of the main group.

current_command[source]#

The current click command the user is in.

current_ctx[source]#

The most recently created click context object, after parsing args

current_group[source]#

The current click group the user is in.

current_param[source]#

The current click parameter the user is on.

double_dash_found[source]#

Determines whether there’s a '--' in args.

remaining_params: list[Parameter][source]#

List of unused parameters of the current command.

click_repl.parser._resolve_incomplete(document_text: str) tuple[tuple[str, ...], Incomplete][source]#

Resolves the last incomplete string token from the prompt to generate suggestions based on it.

Parameters:

document_text – The text currently in the prompt.

Returns:

tuple[tuple[str,...],Incomplete]

A tuple that containing:
  • A list of text, lexically split from the text in prompt.

  • An Incomplete object that has the recent incomplete text token.

click_repl.parser._resolve_repl_input_state(cli_ctx: Context, current_ctx: Context, args: tuple[str, ...]) ReplInputState[source]#

Initializes ReplInputState class if its arguments are not cached. Otherwise, returns the cached ReplInputState object.

Parameters:
  • cli_ctx – The click context object of the parent group.

  • current_ctx – The current click context object.

  • args – Tuple of strings containing the arguments.

Returns:

ReplInputState – Object that describes the current input state.

click_repl.parser._resolve_state(ctx: Context, document_text: str) tuple[Context, ReplInputState, Incomplete][source]#

Resolves the input state of the arguments in the REPL prompt.

Parameters:
  • ctx – The current click context object of the parent group.

  • document_text – The text currently in the prompt.

Returns:

tuple[Context,ReplInputState,Incomplete]

A tuple that contains:
  • click context object constructed from parsing the given input from prompt.

  • Current REPL input state object.

  • Object that holds the incomplete text token that requires suggestions.

Utils#

Utilities to facilitate the functionality of the module.

click_repl.utils.is_param_value_incomplete(ctx: Context, param: Parameter, check_if_tuple_has_none: bool = True) bool[source]#

Checks whether the given parameter has recieved its values completely.

Parameters:
  • ctx – A click context object corresponding to the parameter.

  • param – A click parameter object to check its value after parsing.

  • check_if_tuple_has_none – Indicates whether the given parameter stores multiple values in a tuple, and the tuple has None in it.

Returns:

boolTrue if the given parameter has received all of its necessary values from the prompt, otherwise False.

click_repl.utils.iterate_command_params(command: Command) Generator[Parameter, None, None][source]#

Iterate over parameters of a command in an order such that the Argument with nargs = -1 will be yielded at the very end.

Parameters:

command – A click command object to iterate over its parameters.

Yields:

click.Parameter – The parameters of the given command, yielding the nargs=-1 parameter at last.

Raises:

ArgumentPositionError – If the Argument object with nargs=-1 is not defined at the very end among other parameters.

click_repl.utils.print_error(text: str) None[source]#

Prints the given text to stderr, in red colour.

Parameters:

text – The text to be printed.

Exceptions#

Exceptional classes required for the module.

exception click_repl.exceptions.ArgumentPositionError(command: Command, argument: Argument, position: int)[source]#

Exception raised when an Argument with nargs = -1 is not defined at the rightmost end of the parameter list.

This exception indicates that the given command has an argument with nargs=-1 defined within the other parameters. However, an argument with nargs=-1 must be defined at the end of the parameter list. This is because an argument with nargs=-1 consumes all the incoming values as the remaining values from the REPL prompt, and any other parameter defined after it will not receive any value.

Parameters:
  • command – The click command object that contains the argument.

  • argument – The click argument object that violates the position rule.

  • position – The index of the disarranged nargs=-1 argument in the parameter list of the given command.

exception click_repl.exceptions.ExitReplException[source]#

Exception raised to stop the REPL of the click_repl app.

exception click_repl.exceptions.InternalCommandException[source]#

Base Class for all exceptions raised by the InternalCommandSystem.

This class is used to replace errors raised inside the InternalCommandSystem class in order to display their error messages separately in the REPL.

exception click_repl.exceptions.InternalCommandNotFound[source]#

Exception raised when the given command name is not an internal command.

exception click_repl.exceptions.ParserError[source]#

Exception raised when parsing given input for click objects fails.

exception click_repl.exceptions.PrefixNotFound[source]#

Exception raised when the prefix of an internal command is not found while attempting to execute a query.

exception click_repl.exceptions.SamePrefix(prefix_str: str)[source]#

Exception raised when both system_command_prefix in InternalCommandSystem are assigned as the same prefix string.

Parameters:

prefix_str – The prefix string that is assigned to both internal_command_prefix and system_command_prefix.

exception click_repl.exceptions.WrongType(var: Any, var_name: str, expected_type: str)[source]#

Exception raised when an object with an invalid type is passed to one of the methods in InternalCommandSystem.

Parameters:
  • var – The variable that has wrong or unexpected type.

  • var_name – The name of the variable passed through the var parameter.

  • expected_type – A string that describes the expected type.

Custom Click Utilities#

Customized click module utilities with modifications to benefit the functionality of click-repl module.

Parsers#

class click_repl.click_custom.parser.ArgumentParamParser(obj: CoreArgument, dest: str | None, nargs: int = 1)[source]#

Subclass of Argument, but modified to fill None for empty values for an Argument with nargs != 1.

Parameters:
  • obj – The click argument object.

  • dest – The name of the obj.

  • nargs – The nargs of the obj.

References

Argument

class click_repl.click_custom.parser.ReplOptionParser(ctx: Context)[source]#

Subclass of OptionParser, modified to fill in None values for empty values for Argument with nargs != 1.

Parameters:

ctx – The current click context object, constructed from the text currently in the prompt.

References

OptionParser

add_argument(obj: Argument, dest: str | None, nargs: int = 1) None[source]#

Adds a positional argument named dest to the parser.

The obj can be used to identify the option in the order list that is returned from the parser.

click_repl.click_custom.parser.get_option_flags_sep(option_names: list[str]) str[source]#

Returns the character to separate the given list of option names.

Parameters:

option_names – List of option names

Returns:

str – Character that separates the option names

click_repl.click_custom.parser.order_option_names(option_names: Sequence[str]) list[str][source]#

Orders all the option names based on the length of their prefixes.

Parameters:

option_names – List of option names of a click option.

Returns:

list[str] – List of option names, ordered based on their prefix length.

Shell Completion#

Utils#

Others#

Global Values#

Global variables, values, and functions that are accessed across all the files in this module.

click_repl.globals_.get_current_repl_ctx() ReplContext | NoReturn[source]#
click_repl.globals_.get_current_repl_ctx(silent: bool = False) ReplContext | NoReturn | None

Retrieves the current click-repl context.

This function provides a way to access the context from anywhere in the code. This function serves as a more implicit alternative to the pass_context() decorator.

Parameters:

silent – If set to True, the function returns None if no context is available. The default behavior is to raise a RuntimeError.

Returns:

ReplContext | None – REPL context object if available, or None if silent is True.

Raises:

RuntimeError – If there’s no context object in the stack and silent is False.

click_repl.globals_.CLICK_REPL_DEV_ENV[source]#

Environmental flag for click-repl. Enable it only for debugging purposes.

Style Config#

Default tokens style configurations.

click_repl.styles.DEFAULT_BOTTOMBAR_STYLE_CONFIG[source]#

Default token style configuration for BottomBar

click_repl.styles.DEFAULT_COMPLETION_STYLE_CONFIG[source]#

Default token style configuration for ClickCompleter

click_repl.styles.DEFAULT_PROMPTSESSION_STYLE_CONFIG[source]#

Default token style configuration for PromptSession

Proxies#

Proxy objects to modify the parsing method of click objects.

class click_repl.proxies.Proxy(obj: T)[source]#

Base class for creating proxy objects that customize attribute access behavior.

Parameters:

obj – Object to which attribute access is delegated.

get_obj() Any[source]#

Gets the underlying object.

Returns:

Any – The underlying object to which attribute access is delegated.

proxy_delattr(name: str) None[source]#

Proxy attribute deletion for internal use.

Parameters:

name – The name of the attribute to delete.

proxy_getattr(name: str) Any[source]#

Proxy attribute access for internal use.

Parameters:

name – The name of the attribute to access.

Returns:

Any – The value of the accessed attribute.

proxy_setattr(name: str, value: Any) None[source]#

Proxy attribute assignment for internal use.

Parameters:
  • name – The name of the attribute to assign.

  • value – The value to assign to the attribute.

revoke_changes() None[source]#

Revoke any changes made to the underlying object.

Raises:

NotImplementedError – This method is meant to be overridden by subclasses.

class click_repl.proxies.ProxyArgument(obj: Argument)[source]#

Proxy class for Argument objects, enabling modification of their behavior during the processing and consuming values.

This class overrides the process_value() method to return missing values as they are, even if they are incomplete or not provided.

Parameters:

obj – The Argument object that needs to be proxied.

class click_repl.proxies.ProxyCommand(obj: Command)[source]#

Proxy class for Command objects that modifies their options parser.

This class overrides the make_parser() method to use the custom parser implementation provided by ReplOptionParser.

Parameters:

obj – The click command object that needs to be proxied.

make_parser(ctx: Context) ReplOptionParser[source]#

Creates the underlying option parser for this command.

revoke_changes() None[source]#

Revoke any changes made to the underlying object.

Raises:

NotImplementedError – This method is meant to be overridden by subclasses.

class click_repl.proxies.ProxyCommandCollection(obj: CommandCollection)[source]#

Proxy class for ProxyCommandCollection objects that modifies their options parser.

This class overrides the make_parser() method to use the custom parser implementation provided by ReplOptionParser.

Parameters:

obj – The click group object that needs to be proxied.

class click_repl.proxies.ProxyGroup(obj: Group)[source]#

Proxy class for Group objects that modifies their options parser.

This class overrides the make_parser() method to use the custom parser implementation provided by ReplOptionParser.

Parameters:

obj – The click group object that needs to be proxied.

revoke_changes() None[source]#

Revoke any changes made to the underlying object.

Raises:

NotImplementedError – This method is meant to be overridden by subclasses.

class click_repl.proxies.ProxyOption(obj: Option)[source]#

Proxy class for Option object, enabling modification of their behavior during the processing and consuming values and also prevent prompting for value in the REPL.

This class overrides the process_value() method to return missing values as they are, even if they are incomplete or not provided.

Parameters:

obj – The click.Option object that needs to be proxied.

prompt_for_value(ctx: Context) Any[source]#

This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result.

class click_repl.proxies.ProxyParameter(obj: Parameter)[source]#

Generic proxy class for Parameter objects that modifies its behavior for processing and consuming values.

This class overrides the process_value() method to return missing values as they are, even if they are incomplete or not provided.

Parameters:

obj – The click.Parameter object that needs to be proxied.

click_repl.proxies.create_proxy_command(obj: Command) ProxyCommand[source]#
click_repl.proxies.create_proxy_command(obj: Group) ProxyGroup
click_repl.proxies.create_proxy_command(obj: CommandCollection) ProxyCommandCollection

Wraps the given Command object within a proxy object.

Parameters:

obj – Command object that needs to be wrapped in a proxy object.

Returns:

ProxyCommand | ProxyGroup | ProxyCommandCollection – Proxy wrapper for the Command objects.

click_repl.proxies.create_proxy_param(obj: Parameter) Parameter[source]#
click_repl.proxies.create_proxy_param(obj: Option) ProxyOption
click_repl.proxies.create_proxy_param(obj: Argument) ProxyArgument

Wraps the given Parameter object within a proxy object.

Parameters:

obj – Parameter object that needs to be wrapped in a proxy object.

Returns:

ProxyParameter – Proxy wrapper for the Parameter objects.