class documentation

class Context:

View In Hierarchy

The context is a special internal object that holds state relevant for the script execution at every single level. It's normally invisible to commands unless they opt-in to getting access to it.

The context is useful as it can pass internal objects around and can control special execution features such as reading data from environment variables.

A context can be used as context manager in which case it will call close on teardown.

Changed in version 8.0: The show_default parameter defaults to the value from the parent context.
Changed in version 7.1: Added the show_default parameter.
Changed in version 4.0: Added the color, ignore_unknown_options, and max_content_width parameters.
Changed in version 3.0: Added the allow_extra_args and allow_interspersed_args parameters.
Changed in version 2.0: Added the resilient_parsing, help_option_names, and token_normalize_func parameters.
Parameters
commandthe command class for this context.
parentthe parent context.
info​_namethe info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it is usually the name of the script, for commands below it it's the name of the script.
objan arbitrary object of user data.
auto​_envvar​_prefixthe prefix to use for automatic environment variables. If this is None then reading from environment variables is disabled. This does not affect manually set environment variables which are always read.
default​_mapa dictionary (like object) with default values for parameters.
terminal​_widththe width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied.
max​_content​_widththe maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right.
resilient​_parsingif this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support.
allow​_extra​_argsif this is set to True then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command.
allow​_interspersed​_argsif this is set to False then options and arguments cannot be mixed. The default is to inherit from the command.
ignore​_unknown​_optionsinstructs click to ignore options it does not know and keeps them for later processing.
help​_option​_namesoptionally a list of strings that define how the default help parameter is named. The default is ['--help'].
token​_normalize​_funcan optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior.
colorcontrols if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output.
show​_defaultShow defaults for all options. If not set, defaults to the value from a parent context. Overrides an option's show_default argument.
Method __enter__ Undocumented
Method __exit__ Undocumented
Method __init__ Undocumented
Method ​_make​_sub​_context Create a new context of the same type as this context, but for a new command.
Method abort Aborts the script.
Method call​_on​_close Register a function to be called when the context tears down.
Method close Invoke all close callbacks registered with call_on_close, and exit all context managers entered with with_resource.
Method ensure​_object Like find_object but sets the innermost object to a new instance of object_type if it does not exist.
Method exit Exits the application with a given exit code.
Method fail Aborts the execution of the program with a specific error message.
Method find​_object Finds the closest object of a given type.
Method find​_root Finds the outermost context.
Method forward Similar to invoke but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands.
Method get​_help Helper method to get formatted help page for the current context and command.
Method get​_parameter​_source Get the source of a parameter. This indicates the location from which the value of the parameter was obtained.
Method get​_usage Helper method to get formatted usage string for the current context and command.
Method invoke Invokes a command callback in exactly the way it expects. There are two ways to invoke this method:
Method lookup​_default Get the default for a parameter from default_map.
Method make​_formatter Creates the ~click.HelpFormatter for the help and usage output.
Method scope No summary
Method set​_parameter​_source Set the source of a parameter. This indicates the location from which the value of the parameter was obtained.
Method to​_info​_dict Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire CLI structure.
Method with​_resource Register a resource as if it were used in a with statement. The resource will be cleaned up when the context is popped.
Instance Variable ​_close​_callbacks Undocumented
Instance Variable ​_depth Undocumented
Instance Variable ​_exit​_stack Undocumented
Instance Variable ​_meta Undocumented
Instance Variable ​_parameter​_source Undocumented
Instance Variable allow​_extra​_args Undocumented
Instance Variable allow​_interspersed​_args Undocumented
Instance Variable args Undocumented
Instance Variable auto​_envvar​_prefix Undocumented
Instance Variable color Undocumented
Instance Variable command Undocumented
Instance Variable default​_map Undocumented
Instance Variable help​_option​_names Undocumented
Instance Variable ignore​_unknown​_options Undocumented
Instance Variable info​_name Undocumented
Instance Variable invoked​_subcommand Undocumented
Instance Variable max​_content​_width Undocumented
Instance Variable obj Undocumented
Instance Variable params Undocumented
Instance Variable parent Undocumented
Instance Variable protected​_args Undocumented
Instance Variable resilient​_parsing Undocumented
Instance Variable show​_default Undocumented
Instance Variable terminal​_width Undocumented
Instance Variable token​_normalize​_func Undocumented
Property command​_path The computed command path. This is used for the usage information on the help page. It's automatically created by combining the info names of the chain of contexts to the root.
Property meta No summary
def __enter__(self):

Undocumented

Returns
ContextUndocumented
def __exit__(self, exc_type, exc_value, tb):

Undocumented

def __init__(self, command, parent=None, info_name=None, obj=None, auto_envvar_prefix=None, default_map=None, terminal_width=None, max_content_width=None, resilient_parsing=False, allow_extra_args=None, allow_interspersed_args=None, ignore_unknown_options=None, help_option_names=None, token_normalize_func=None, color=None, show_default=None):

Undocumented

Parameters
command:CommandUndocumented
parent:t.Optional[Context]Undocumented
info​_name:t.Optional[str]Undocumented
obj:t.Optional[t.Any]Undocumented
auto​_envvar​_prefix:t.Optional[str]Undocumented
default​_map:t.Optional[t.Dict[str, t.Any]]Undocumented
terminal​_width:t.Optional[int]Undocumented
max​_content​_width:t.Optional[int]Undocumented
resilient​_parsing:boolUndocumented
allow​_extra​_args:t.Optional[bool]Undocumented
allow​_interspersed​_args:t.Optional[bool]Undocumented
ignore​_unknown​_options:t.Optional[bool]Undocumented
help​_option​_names:t.Optional[t.List[str]]Undocumented
token​_normalize​_func:t.Optional[t.Callable[[str], str]]Undocumented
color:t.Optional[bool]Undocumented
show​_default:t.Optional[bool]Undocumented
def _make_sub_context(self, command):
Create a new context of the same type as this context, but for a new command.
Parameters
command:CommandUndocumented
Returns
ContextUndocumented
Unknown Field: meta
private
def abort(self):
Aborts the script.
Returns
te.NoReturnUndocumented
def call_on_close(self, f):

Register a function to be called when the context tears down.

This can be used to close resources opened during the script execution. Resources that support Python's context manager protocol which would be used in a with statement should be registered with with_resource instead.

Parameters
f:t.Callable[..., t.Any]The function to execute on teardown.
Returns
t.Callable[..., t.Any]Undocumented
def close(self):
Invoke all close callbacks registered with call_on_close, and exit all context managers entered with with_resource.
def ensure_object(self, object_type):
Like find_object but sets the innermost object to a new instance of object_type if it does not exist.
Parameters
object​_type:t.Type[V]Undocumented
Returns
VUndocumented
def exit(self, code=0):
Exits the application with a given exit code.
Parameters
code:intUndocumented
Returns
te.NoReturnUndocumented
def fail(self, message):
Aborts the execution of the program with a specific error message.
Parameters
message:strthe error message to fail with.
Returns
te.NoReturnUndocumented
def find_object(self, object_type):
Finds the closest object of a given type.
Parameters
object​_type:t.Type[V]Undocumented
Returns
t.Optional[V]Undocumented
def find_root(self):
Finds the outermost context.
Returns
ContextUndocumented
def forward(__self, __cmd, *args, **kwargs):

Similar to invoke but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands.

Changed in version 8.0: All kwargs are tracked in params so they will be passed if forward is called at multiple levels.
Parameters
__selfUndocumented
__cmd:CommandUndocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.AnyUndocumented
def get_help(self):
Helper method to get formatted help page for the current context and command.
Returns
strUndocumented
def get_parameter_source(self, name):

Get the source of a parameter. This indicates the location from which the value of the parameter was obtained.

This can be useful for determining when a user specified a value on the command line that is the same as the default value. It will be ~click.core.ParameterSource.DEFAULT only if the value was actually taken from the default.

Changed in version 8.0: Returns None if the parameter was not provided from any source.
Parameters
name:strThe name of the parameter.
Returns
ParameterSourceUndocumented
def get_usage(self):
Helper method to get formatted usage string for the current context and command.
Returns
strUndocumented
def invoke(__self, __callback, *args, **kwargs):

Invokes a command callback in exactly the way it expects. There are two ways to invoke this method:

  1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function.
  2. the first argument is a click command object. In that case all arguments are forwarded as well but proper click parameters (options and click arguments) must be keyword arguments and Click will fill in defaults.

Note that before Click 3.2 keyword arguments were not properly filled in against the intention of this code and no context was created. For more information about this change and why it was done in a bugfix release see :ref:`upgrade-to-3.2`.

Changed in version 8.0: All kwargs are tracked in params so they will be passed if forward is called at multiple levels.
Parameters
__selfUndocumented
__callback:t.Union[Command, t.Callable[..., t.Any]]Undocumented
*args:t.AnyUndocumented
**kwargs:t.AnyUndocumented
Returns
t.AnyUndocumented
def lookup_default(self, name, call=True):

Get the default for a parameter from default_map.

Changed in version 8.0: Added the call parameter.
Parameters
name:strName of the parameter.
call:boolIf the default is a callable, call it. Disable to return the callable instead.
Returns
t.Optional[t.Any]Undocumented
def make_formatter(self):

Creates the ~click.HelpFormatter for the help and usage output.

To quickly customize the formatter class used without overriding this method, set the formatter_class attribute.

Changed in version 8.0: Added the formatter_class attribute.
Returns
HelpFormatterUndocumented
@contextmanager
def scope(self, cleanup=True):

This helper method can be used with the context object to promote it to the current thread local (see get_current_context). The default behavior of this is to invoke the cleanup functions which can be disabled by setting cleanup to False. The cleanup functions are typically used for things such as closing file handles.

If the cleanup is intended the context object can also be directly used as a context manager.

Example usage:

with ctx.scope():
    assert get_current_context() is ctx

This is equivalent:

with ctx:
    assert get_current_context() is ctx
New in version 5.0.
Parameters
cleanup:boolcontrols if the cleanup functions should be run or not. The default is to run these functions. In some situations the context only wants to be temporarily pushed in which case this can be disabled. Nested pushes automatically defer the cleanup.
Returns
t.Iterator[Context]Undocumented
def set_parameter_source(self, name, source):
Set the source of a parameter. This indicates the location from which the value of the parameter was obtained.
Parameters
name:strThe name of the parameter.
source:ParameterSourceA member of ~click.core.ParameterSource.
def to_info_dict(self):

Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire CLI structure.

with Context(cli) as ctx:
    info = ctx.to_info_dict()
New in version 8.0.
Returns
t.Dict[str, t.Any]Undocumented
def with_resource(self, context_manager):

Register a resource as if it were used in a with statement. The resource will be cleaned up when the context is popped.

Uses contextlib.ExitStack.enter_context. It calls the resource's __enter__() method and returns the result. When the context is popped, it closes the stack, which calls the resource's __exit__() method.

To register a cleanup function for something that isn't a context manager, use call_on_close. Or use something from contextlib to turn it into a context manager first.

@click.group()
@click.option("--name")
@click.pass_context
def cli(ctx):
    ctx.obj = ctx.with_resource(connect_db(name))
New in version 8.0.
Parameters
context​_manager:t.ContextManager[V]The context manager to enter.
Returns
VWhatever context_manager.__enter__() returns.
_close_callbacks: t.List[t.Callable[[], t.Any]] =

Undocumented

_depth: int =

Undocumented

_exit_stack =

Undocumented

_meta: t.Dict[str, t.Any] =

Undocumented

_parameter_source: t.Dict[str, ParameterSource] =

Undocumented

allow_extra_args =

Undocumented

allow_interspersed_args: bool =

Undocumented

args: t.List[str] =

Undocumented

auto_envvar_prefix: t.Optional[str] =

Undocumented

color: t.Optional[bool] =

Undocumented

command =

Undocumented

default_map: t.Optional[t.Dict[str, t.Any]] =

Undocumented

help_option_names: t.List[str] =

Undocumented

ignore_unknown_options: bool =

Undocumented

info_name =

Undocumented

invoked_subcommand: t.Optional[str] =

Undocumented

max_content_width: t.Optional[int] =

Undocumented

obj =

Undocumented

params: t.Dict[str, t.Any] =

Undocumented

parent =

Undocumented

protected_args: t.List[str] =

Undocumented

resilient_parsing: bool =

Undocumented

show_default: t.Optional[bool] =

Undocumented

terminal_width: t.Optional[int] =

Undocumented

token_normalize_func: t.Optional[t.Callable[[str], str]] =

Undocumented

@property
command_path: str =
The computed command path. This is used for the usage information on the help page. It's automatically created by combining the info names of the chain of contexts to the root.
@property
meta: t.Dict[str, t.Any] =

This is a dictionary which is shared with all the contexts that are nested. It exists so that click utilities can store some state here if they need to. It is however the responsibility of that code to manage this dictionary well.

The keys are supposed to be unique dotted strings. For instance module paths are a good choice for it. What is stored in there is irrelevant for the operation of click. However what is important is that code that places data here adheres to the general semantics of the system.

Example usage:

LANG_KEY = f'{__name__}.lang'

def set_language(value):
    ctx = get_current_context()
    ctx.meta[LANG_KEY] = value

def get_language():
    return get_current_context().meta.get(LANG_KEY, 'en_US')
New in version 5.0.