class Context: (source)
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 |
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 |
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 |
Finds the closest object of a given type. |
Method | find |
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 |
Helper method to get formatted help page for the current context and command. |
Method | get |
Get the source of a parameter. This indicates the location from which the value of the parameter was obtained. |
Method | get |
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 |
Get the default for a parameter from :attr:`default_map`. |
Method | make |
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 |
Set the source of a parameter. This indicates the location from which the value of the parameter was obtained. |
Method | to |
Gather information that could be useful for a tool generating user-facing documentation. This traverses the entire CLI structure. |
Method | with |
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 |
Undocumented |
Instance Variable | allow |
Undocumented |
Instance Variable | args |
Undocumented |
Instance Variable | auto |
Undocumented |
Instance Variable | color |
Undocumented |
Instance Variable | command |
Undocumented |
Instance Variable | default |
Undocumented |
Instance Variable | help |
Undocumented |
Instance Variable | ignore |
Undocumented |
Instance Variable | info |
Undocumented |
Instance Variable | invoked |
Undocumented |
Instance Variable | max |
Undocumented |
Instance Variable | obj |
Undocumented |
Instance Variable | params |
Undocumented |
Instance Variable | parent |
Undocumented |
Instance Variable | protected |
Undocumented |
Instance Variable | resilient |
Undocumented |
Instance Variable | show |
Undocumented |
Instance Variable | terminal |
Undocumented |
Instance Variable | token |
Undocumented |
Property | command |
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 |
Create a new context of the same type as this context, but for a new command. |
Instance Variable | _close |
Undocumented |
Instance Variable | _depth |
Undocumented |
Instance Variable | _exit |
Undocumented |
Instance Variable | _meta |
Undocumented |
Instance Variable | _opt |
Undocumented |
Instance Variable | _parameter |
Undocumented |
Undocumented
Parameters | |
command:Command | Undocumented |
parent:t.Optional[ | Undocumented |
infot.Optional[ | Undocumented |
obj:t.Optional[ | Undocumented |
autot.Optional[ | Undocumented |
defaultt.Optional[ | Undocumented |
terminalt.Optional[ | Undocumented |
maxt.Optional[ | Undocumented |
resilientbool | Undocumented |
allowt.Optional[ | Undocumented |
allowt.Optional[ | Undocumented |
ignoret.Optional[ | Undocumented |
helpt.Optional[ | Undocumented |
tokent.Optional[ | Undocumented |
color:t.Optional[ | Undocumented |
showt.Optional[ | Undocumented |
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[ | Undocumented |
Returns | |
t.Callable[ | Undocumented |
Invoke all close callbacks registered with :meth:`call_on_close`, and exit all context managers entered with :meth:`with_resource`.
Exits the application with a given exit code.
Parameters | |
code:int | Undocumented |
Returns | |
te.NoReturn | Undocumented |
Aborts the execution of the program with a specific error message. :param message: the error message to fail with.
Parameters | |
message:str | Undocumented |
Returns | |
te.NoReturn | Undocumented |
Finds the closest object of a given type.
Parameters | |
objectt.Type[ | Undocumented |
Returns | |
t.Optional[ | Undocumented |
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 | |
__self | Undocumented |
__cmd:Command | Undocumented |
*args:t.Any | Undocumented |
**kwargs:t.Any | Undocumented |
Returns | |
t.Any | Undocumented |
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:str | Undocumented |
Returns | |
t.Optional[ | Undocumented |
Helper method to get formatted usage string for the current context and command.
Returns | |
str | Undocumented |
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 | |
__self | Undocumented |
__callback:t.Union[ | Undocumented |
*args:t.Any | Undocumented |
**kwargs:t.Any | Undocumented |
Returns | |
t.Any | Undocumented |
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:str | Undocumented |
call:bool | Undocumented |
Returns | |
t.Optional[ | Undocumented |
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 | |
HelpFormatter | Undocumented |
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:bool | Undocumented |
Returns | |
t.Iterator[ | Undocumented |
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:str | Undocumented |
source:ParameterSource | Undocumented |
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 | |
contextt.ContextManager[ | Undocumented |
Returns | |
V | Undocumented |
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