class documentation

class Context: (source)

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 :meth:`close` on teardown. :param command: the command class for this context. :param parent: the parent context. :param info_name: the 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. :param obj: an arbitrary object of user data. :param auto_envvar_prefix: the 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. :param default_map: a dictionary (like object) with default values for parameters. :param terminal_width: the width of the terminal. The default is inherit from parent context. If no context defines the terminal width then auto detection will be applied. :param max_content_width: the 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. :param resilient_parsing: if 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. :param allow_extra_args: if 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. :param allow_interspersed_args: if this is set to `False` then options and arguments cannot be mixed. The default is to inherit from the command. :param ignore_unknown_options: instructs click to ignore options it does not know and keeps them for later processing. :param help_option_names: optionally a list of strings that define how the default help parameter is named. The default is ``['--help']``. :param token_normalize_func: an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case insensitive behavior. :param color: controls 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. :param show_default: Show the default value for commands. If this value is not set, it defaults to the value from the parent context. ``Command.show_default`` overrides this default for the specific command. .. versionchanged:: 8.1 The ``show_default`` parameter is overridden by ``Command.show_default``, instead of the other way around. .. versionchanged:: 8.0 The ``show_default`` parameter defaults to the value from the parent context. .. versionchanged:: 7.1 Added the ``show_default`` parameter. .. versionchanged:: 4.0 Added the ``color``, ``ignore_unknown_options``, and ``max_content_width`` parameters. .. versionchanged:: 3.0 Added the ``allow_extra_args`` and ``allow_interspersed_args`` parameters. .. versionchanged:: 2.0 Added the ``resilient_parsing``, ``help_option_names``, and ``token_normalize_func`` parameters.

Method __enter__ Undocumented
Method __exit__ Undocumented
Method __init__ Undocumented
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 :meth:`call_on_close`, and exit all context managers entered with :meth:`with_resource`.
Method ensure_object Like :meth:`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 :meth:`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 :attr:`default_map`.
Method make_formatter Creates the :class:`~click.HelpFormatter` for the help and usage output.
Method scope This helper method can be used with the context object to promote it to the current thread local (see :func:`get_current_context`). The default behavior of this is to invoke the cleanup functions which can be disabled by setting `cleanup` to `False`...
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 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 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.
Method _make_sub_context Create a new context of the same type as this context, but for a new command.
Instance Variable _close_callbacks Undocumented
Instance Variable _depth Undocumented
Instance Variable _exit_stack Undocumented
Instance Variable _meta Undocumented
Instance Variable _opt_prefixes Undocumented
Instance Variable _parameter_source Undocumented
def __enter__(self): (source)

Undocumented

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

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): (source)

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 abort(self): (source)

Aborts the script.

Returns
te.NoReturnUndocumented
def call_on_close(self, f): (source)

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 :meth:`with_resource` instead. :param f: The function to execute on teardown.

Parameters
f:t.Callable[..., t.Any]Undocumented
Returns
t.Callable[..., t.Any]Undocumented
def close(self): (source)

Invoke all close callbacks registered with :meth:`call_on_close`, and exit all context managers entered with :meth:`with_resource`.

def ensure_object(self, object_type): (source)

Like :meth:`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): (source)

Exits the application with a given exit code.

Parameters
code:intUndocumented
Returns
te.NoReturnUndocumented
def fail(self, message): (source)

Aborts the execution of the program with a specific error message. :param message: the error message to fail with.

Parameters
message:strUndocumented
Returns
te.NoReturnUndocumented
def find_object(self, object_type): (source)

Finds the closest object of a given type.

Parameters
object_type:t.Type[V]Undocumented
Returns
t.Optional[V]Undocumented
def find_root(self): (source)

Finds the outermost context.

Returns
ContextUndocumented
def forward(__self, __cmd, *args, **kwargs): (source)

Similar to :meth:`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. .. versionchanged:: 8.0 All ``kwargs`` are tracked in :attr:`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): (source)

Helper method to get formatted help page for the current context and command.

Returns
strUndocumented
def get_parameter_source(self, name): (source)

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 :attr:`~click.core.ParameterSource.DEFAULT` only if the value was actually taken from the default. :param name: The name of the parameter. :rtype: ParameterSource .. versionchanged:: 8.0 Returns ``None`` if the parameter was not provided from any source.

Parameters
name:strUndocumented
Returns
t.Optional[ParameterSource]Undocumented
def get_usage(self): (source)

Helper method to get formatted usage string for the current context and command.

Returns
strUndocumented
def invoke(__self, __callback, *args, **kwargs): (source)

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`. .. versionchanged:: 8.0 All ``kwargs`` are tracked in :attr:`params` so they will be passed if :meth:`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): (source)

Get the default for a parameter from :attr:`default_map`. :param name: Name of the parameter. :param call: If the default is a callable, call it. Disable to return the callable instead. .. versionchanged:: 8.0 Added the ``call`` parameter.

Parameters
name:strUndocumented
call:boolUndocumented
Returns
t.Optional[t.Any]Undocumented
def make_formatter(self): (source)

Creates the :class:`~click.HelpFormatter` for the help and usage output. To quickly customize the formatter class used without overriding this method, set the :attr:`formatter_class` attribute. .. versionchanged:: 8.0 Added the :attr:`formatter_class` attribute.

Returns
HelpFormatterUndocumented
@contextmanager
def scope(self, cleanup=True): (source)

This helper method can be used with the context object to promote it to the current thread local (see :func:`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 .. versionadded:: 5.0 :param cleanup: controls 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.

Parameters
cleanup:boolUndocumented
Returns
t.Iterator[Context]Undocumented
def set_parameter_source(self, name, source): (source)

Set the source of a parameter. This indicates the location from which the value of the parameter was obtained. :param name: The name of the parameter. :param source: A member of :class:`~click.core.ParameterSource`.

Parameters
name:strUndocumented
source:ParameterSourceUndocumented
def to_info_dict(self): (source)

Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire CLI structure. .. code-block:: python with Context(cli) as ctx: info = ctx.to_info_dict() .. versionadded:: 8.0

Returns
t.Dict[str, t.Any]Undocumented
def with_resource(self, context_manager): (source)

Register a resource as if it were used in a ``with`` statement. The resource will be cleaned up when the context is popped. Uses :meth:`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 :meth:`call_on_close`. Or use something from :mod:`contextlib` to turn it into a context manager first. .. code-block:: python @click.group() @click.option("--name") @click.pass_context def cli(ctx): ctx.obj = ctx.with_resource(connect_db(name)) :param context_manager: The context manager to enter. :return: Whatever ``context_manager.__enter__()`` returns. .. versionadded:: 8.0

Parameters
context_manager:t.ContextManager[V]Undocumented
Returns
VUndocumented
allow_extra_args = (source)

Undocumented

allow_interspersed_args: bool = (source)

Undocumented

Undocumented

auto_envvar_prefix: t.Optional[str] = (source)

Undocumented

Undocumented

command = (source)

Undocumented

Undocumented

help_option_names: t.List[str] = (source)

Undocumented

ignore_unknown_options: bool = (source)

Undocumented

info_name = (source)

Undocumented

invoked_subcommand: t.Optional[str] = (source)

Undocumented

max_content_width: t.Optional[int] = (source)

Undocumented

Undocumented

Undocumented

parent = (source)

Undocumented

protected_args: t.List[str] = (source)

Undocumented

resilient_parsing: bool = (source)

Undocumented

show_default: t.Optional[bool] = (source)

Undocumented

terminal_width: t.Optional[int] = (source)

Undocumented

token_normalize_func: t.Optional[t.Callable[[str], str]] = (source)

Undocumented

@property
command_path: str = (source)

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.

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') .. versionadded:: 5.0

def _make_sub_context(self, command): (source)

Create a new context of the same type as this context, but for a new command. :meta private:

Parameters
command:CommandUndocumented
Returns
ContextUndocumented
_close_callbacks: t.List[t.Callable[[], t.Any]] = (source)

Undocumented

_depth: int = (source)

Undocumented

_exit_stack = (source)

Undocumented

Undocumented

_opt_prefixes: t.Set[str] = (source)

Undocumented

_parameter_source: t.Dict[str, ParameterSource] = (source)

Undocumented