hpcflow.sdk.cli.ErrorPropagatingClickContext#

class hpcflow.sdk.cli.ErrorPropagatingClickContext(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)#

Bases: Context

A click Context class that passes on exception information.

Using the standard click.Context class, exceptions raised when using a resource specified with ctx.with_resource(my_ctx_manager()) are not passed on to the __exit__ method of my_ctx_manager. See: pallets/click#2447.

Examples

>>> @click.group()
... @click.pass_context
... def cli(ctx):
...     ctx.with_resource(my_context_manager())
... cli.context_class = ErrorPropagatingClickContext

Methods

abort

Aborts the script.

call_on_close

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

close

Invoke all close callbacks registered with call_on_close(), and exit all context managers entered with with_resource().

ensure_object

Like find_object() but sets the innermost object to a new instance of object_type if it does not exist.

exit

Exits the application with a given exit code.

fail

Aborts the execution of the program with a specific error message.

find_object

Finds the closest object of a given type.

find_root

Finds the outermost context.

forward

Similar to invoke() but fills in default keyword arguments from the current context if the other command expects it.

get_help

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

get_parameter_source

Get the source of a parameter.

get_usage

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

invoke

Invokes a command callback in exactly the way it expects.

lookup_default

Get the default for a parameter from default_map.

make_formatter

Creates the HelpFormatter for the help and usage output.

scope

This helper method can be used with the context object to promote it to the current thread local (see get_current_context()).

set_parameter_source

Set the source of a parameter.

to_info_dict

Gather information that could be useful for a tool generating user-facing documentation.

with_resource

Register a resource as if it were used in a with statement.

Attributes

command_path

The computed command path.

meta

This is a dictionary which is shared with all the contexts that are nested.

parent

the parent context or None if none exists.

command

the Command for this context.

info_name

the descriptive information name

params

Map of parameter names to their parsed values.

args

the leftover arguments.

protected_args

protected arguments.

obj

the user object stored.

invoked_subcommand

This flag indicates if a subcommand is going to be executed.

terminal_width

The width of the terminal (None is autodetection).

max_content_width

The maximum width of formatted content (None implies a sensible default which is 80 for most things).

allow_extra_args

Indicates if the context allows extra args or if it should fail on parsing.

allow_interspersed_args

Indicates if the context allows mixing of arguments and options or not.

ignore_unknown_options

Instructs click to ignore options that a command does not understand and will store it on the context for later processing.

help_option_names

The names for the help options.

token_normalize_func

An optional normalization function for tokens.

resilient_parsing

Indicates if resilient parsing is enabled.

color

Controls if styling output is wanted or not.

show_default

Show option default values when formatting help text.

Parameters:
  • command (Command) –

  • parent (Context | None) –

  • info_name (str | None) –

  • obj (Any | None) –

  • auto_envvar_prefix (str | None) –

  • default_map (MutableMapping[str, Any] | None) –

  • terminal_width (int | None) –

  • max_content_width (int | None) –

  • resilient_parsing (bool) –

  • allow_extra_args (bool | None) –

  • allow_interspersed_args (bool | None) –

  • ignore_unknown_options (bool | None) –

  • help_option_names (List[str] | None) –

  • token_normalize_func (Callable[[str], str] | None) –

  • color (bool | None) –

  • show_default (bool | None) –

abort()#

Aborts the script.

Return type:

te.NoReturn

allow_extra_args#

Indicates if the context allows extra args or if it should fail on parsing.

New in version 3.0.

allow_interspersed_args: bool#

Indicates if the context allows mixing of arguments and options or not.

New in version 3.0.

args: t.List[str]#

the leftover arguments.

call_on_close(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 (Callable[[...], Any]) – The function to execute on teardown.

Return type:

Callable[[…], Any]

close()#

Invoke all close callbacks registered with call_on_close(), and exit all context managers entered with with_resource().

Return type:

None

color: t.Optional[bool]#

Controls if styling output is wanted or not.

command#

the Command for this context.

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.

ensure_object(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 (Type[V]) –

Return type:

V

exit(code=0)#

Exits the application with a given exit code.

Parameters:

code (int) –

Return type:

te.NoReturn

fail(message)#

Aborts the execution of the program with a specific error message.

Parameters:

message (str) – the error message to fail with.

Return type:

te.NoReturn

find_object(object_type)#

Finds the closest object of a given type.

Parameters:

object_type (Type[V]) –

Return type:

V | None

find_root()#

Finds the outermost context.

Return type:

Context

formatter_class#

alias of HelpFormatter

forward(_Context__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:
  • _Context__cmd (Command) –

  • args (Any) –

  • kwargs (Any) –

Return type:

Any

get_help()#

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

Return type:

str

get_parameter_source(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 DEFAULT only if the value was actually taken from the default.

Parameters:

name (str) – The name of the parameter.

Return type:

ParameterSource

Changed in version 8.0: Returns None if the parameter was not provided from any source.

get_usage()#

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

Return type:

str

help_option_names: t.List[str]#

The names for the help options.

ignore_unknown_options: bool#

Instructs click to ignore options that a command does not understand and will store it on the context for later processing. This is primarily useful for situations where you want to call into external programs. Generally this pattern is strongly discouraged because it’s not possibly to losslessly forward all arguments.

New in version 4.0.

info_name#

the descriptive information name

invoke(_Context__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 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:
  • _Context__callback (Command | Callable[[...], V]) –

  • args (Any) –

  • kwargs (Any) –

Return type:

Any | V

invoked_subcommand: t.Optional[str]#

This flag indicates if a subcommand is going to be executed. A group callback can use this information to figure out if it’s being executed directly or because the execution flow passes onwards to a subcommand. By default it’s None, but it can be the name of the subcommand to execute.

If chaining is enabled this will be set to '*' in case any commands are executed. It is however not possible to figure out which ones. If you require this knowledge you should use a result_callback().

lookup_default(name, call=True)#

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.

Return type:

Any | None

Changed in version 8.0: Added the call parameter.

make_formatter()#

Creates the 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.

Return type:

HelpFormatter

max_content_width: t.Optional[int]#

The maximum width of formatted content (None implies a sensible default which is 80 for most things).

property meta: Dict[str, 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.

obj: t.Any#

the user object stored.

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

Map of parameter names to their parsed values. Parameters with expose_value=False are not stored.

parent#

the parent context or None if none exists.

protected_args: t.List[str]#

protected arguments. These are arguments that are prepended to args when certain parsing scenarios are encountered but must be never propagated to another arguments. This is used to implement nested parsing.

resilient_parsing: bool#

Indicates if resilient parsing is enabled. In that case Click will do its best to not cause any failures and default values will be ignored. Useful for completion.

scope(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 (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.

Return type:

Iterator[Context]

set_parameter_source(name, source)#

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

Parameters:
  • name (str) – The name of the parameter.

  • source (ParameterSource) – A member of ParameterSource.

Return type:

None

show_default: t.Optional[bool]#

Show option default values when formatting help text.

terminal_width: t.Optional[int]#

The width of the terminal (None is autodetection).

to_info_dict()#

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.

Return type:

Dict[str, Any]

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

An optional normalization function for tokens. This is options, choices, commands etc.

with_resource(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))
Parameters:

context_manager (ContextManager[V, bool | None]) – The context manager to enter.

Returns:

Whatever context_manager.__enter__() returns.

Return type:

V

New in version 8.0.