class Context:
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.
Parameters | |
command | the command class for this context. |
parent | the parent context. |
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. |
obj | an arbitrary object of user data. |
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. |
default_map | a dictionary (like object) with default values for parameters. |
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. |
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. |
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. |
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. |
allow_interspersed_args | if this is set to False then options
and arguments cannot be mixed. The
default is to inherit from the command. |
ignore_unknown_options | instructs click to ignore options it does not know and keeps them for later processing. |
help_option_names | optionally a list of strings that define how the default help parameter is named. The default is ['--help']. |
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. |
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. |
show_default | Show 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 |
Undocumented
Parameters | |
command:Command | Undocumented |
parent:t.Optional[ | Undocumented |
info_name:t.Optional[ | Undocumented |
obj:t.Optional[ | Undocumented |
auto_envvar_prefix:t.Optional[ | Undocumented |
default_map:t.Optional[ | Undocumented |
terminal_width:t.Optional[ | Undocumented |
max_content_width:t.Optional[ | Undocumented |
resilient_parsing:bool | Undocumented |
allow_extra_args:t.Optional[ | Undocumented |
allow_interspersed_args:t.Optional[ | Undocumented |
ignore_unknown_options:t.Optional[ | Undocumented |
help_option_names:t.Optional[ | Undocumented |
token_normalize_func:t.Optional[ | Undocumented |
color:t.Optional[ | Undocumented |
show_default:t.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 with_resource
instead.
Parameters | |
f:t.Callable[ | The function to execute on teardown. |
Returns | |
t.Callable[ | Undocumented |
call_on_close
, and exit all context managers entered
with with_resource
.find_object
but sets the innermost object to a
new instance of object_type
if it does not exist.Parameters | |
object_type:t.Type[ | Undocumented |
Returns | |
V | Undocumented |
Parameters | |
code:int | Undocumented |
Returns | |
te.NoReturn | Undocumented |
Parameters | |
message:str | the error message to fail with. |
Returns | |
te.NoReturn | Undocumented |
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.
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 |
Returns | |
str | 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 ~click.core.ParameterSource.DEFAULT
only if the
value was actually taken from the default.
Parameters | |
name:str | The name of the parameter. |
Returns | |
ParameterSource | Undocumented |
Returns | |
str | Undocumented |
Invokes a command callback in exactly the way it expects. There are two ways to invoke this method:
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`.
params
so they will be
passed if 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 default_map
.
Parameters | |
name:str | Name of the parameter. |
call:bool | If the default is a callable, call it. Disable to return the callable instead. |
Returns | |
t.Optional[ | Undocumented |
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.
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 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
Parameters | |
cleanup:bool | 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. |
Returns | |
t.Iterator[ | Undocumented |
Parameters | |
name:str | The name of the parameter. |
source:ParameterSource | A member of ~click.core.ParameterSource . |
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()
Returns | |
t.Dict[ | 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 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))
Parameters | |
context_manager:t.ContextManager[ | The context manager to enter. |
Returns | |
V | Whatever context_manager.__enter__() returns. |
str
=
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')