Qucs-S S-parameter Viewer & RF Synthesis Tools
Loading...
Searching...
No Matches
Public Member Functions | Public Attributes | Static Public Attributes | Protected Member Functions | Protected Attributes | List of all members
click.core.Context Class Reference

Public Member Functions

None __init__ (self, Command command, Context|None parent=None, str|None info_name=None, t.Any|None obj=None, str|None auto_envvar_prefix=None, cabc.MutableMapping[str, t.Any]|None default_map=None, int|None terminal_width=None, int|None max_content_width=None, bool resilient_parsing=False, bool|None allow_extra_args=None, bool|None allow_interspersed_args=None, bool|None ignore_unknown_options=None, list[str]|None help_option_names=None, t.Callable[[str], str]|None token_normalize_func=None, bool|None color=None, bool|None show_default=None)
 
list[str] protected_args (self)
 
dict[str, t.Any] to_info_dict (self)
 
Context __enter__ (self)
 
bool|None __exit__ (self, type[BaseException]|None exc_type, BaseException|None exc_value, TracebackType|None tb)
 
cabc.Iterator[Contextscope (self, bool cleanup=True)
 
dict[str, t.Any] meta (self)
 
HelpFormatter make_formatter (self)
 
with_resource (self, AbstractContextManager[V] context_manager)
 
t.Callable[..., t.Any] call_on_close (self, t.Callable[..., t.Any] f)
 
None close (self)
 
str command_path (self)
 
Context find_root (self)
 
V|None find_object (self, type[V] object_type)
 
ensure_object (self, type[V] object_type)
 
t.Any|None lookup_default (self, str name, t.Literal[True] call=True)
 
t.Any|t.Callable[[], t.Any]|None lookup_default (self, str name, t.Literal[False] call=...)
 
t.Any|None lookup_default (self, str name, bool call=True)
 
t.NoReturn fail (self, str message)
 
t.NoReturn abort (self)
 
t.NoReturn exit (self, int code=0)
 
str get_usage (self)
 
str get_help (self)
 
invoke (self, t.Callable[..., V] callback, *t.Any args, **t.Any kwargs)
 
t.Any invoke (self, Command callback, *t.Any args, **t.Any kwargs)
 
t.Any|V invoke (self, Command|t.Callable[..., V] callback, *t.Any args, **t.Any kwargs)
 
t.Any forward (self, Command cmd, *t.Any args, **t.Any kwargs)
 
None set_parameter_source (self, str name, ParameterSource source)
 
ParameterSource|None get_parameter_source (self, str name)
 

Public Attributes

 parent
 
 command
 
 info_name
 
 allow_extra_args
 
 allow_interspersed_args
 
 ignore_unknown_options
 
 auto_envvar_prefix
 
 obj
 

Static Public Attributes

type formatter_class = HelpFormatter
 

Protected Member Functions

bool|None _close_with_exception_info (self, type[BaseException]|None exc_type, BaseException|None exc_value, TracebackType|None tb)
 
Context _make_sub_context (self, Command command)
 

Protected Attributes

 _depth
 
 _exit_stack
 

Detailed Description

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.2
    The ``protected_args`` attribute is deprecated and will be removed in
    Click 9.0. ``args`` will contain remaining unparsed tokens.

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

Member Function Documentation

◆ _close_with_exception_info()

bool | None click.core.Context._close_with_exception_info (   self,
type[BaseException] | None  exc_type,
BaseException | None  exc_value,
TracebackType | None  tb 
)
protected
Unwind the exit stack by calling its :meth:`__exit__` providing the exception
information to allow for exception handling by the various resources registered
using :meth;`with_resource`

:return: Whatever ``exit_stack.__exit__()`` returns.

◆ _make_sub_context()

Context click.core.Context._make_sub_context (   self,
Command  command 
)
protected
Create a new context of the same type as this context, but
for a new command.

:meta private:

◆ abort()

t.NoReturn click.core.Context.abort (   self)
Aborts the script.

◆ call_on_close()

t.Callable[..., t.Any] click.core.Context.call_on_close (   self,
t.Callable[..., t.Any]  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 :meth:`with_resource` instead.

:param f: The function to execute on teardown.

◆ close()

None click.core.Context.close (   self)
Invoke all close callbacks registered with
:meth:`call_on_close`, and exit all context managers entered
with :meth:`with_resource`.

◆ command_path()

str click.core.Context.command_path (   self)
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()

V click.core.Context.ensure_object (   self,
type[V]  object_type 
)
Like :meth:`find_object` but sets the innermost object to a
new instance of `object_type` if it does not exist.

◆ exit()

t.NoReturn click.core.Context.exit (   self,
int   code = 0 
)
Exits the application with a given exit code.

.. versionchanged:: 8.2
    Callbacks and context managers registered with :meth:`call_on_close`
    and :meth:`with_resource` are closed before exiting.

◆ fail()

t.NoReturn click.core.Context.fail (   self,
str  message 
)
Aborts the execution of the program with a specific error
message.

:param message: the error message to fail with.

◆ find_object()

V | None click.core.Context.find_object (   self,
type[V]  object_type 
)
Finds the closest object of a given type.

◆ find_root()

Context click.core.Context.find_root (   self)
Finds the outermost context.

◆ forward()

t.Any click.core.Context.forward (   self,
Command  cmd,
*t.Any  args,
**t.Any  kwargs 
)
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.

◆ get_help()

str click.core.Context.get_help (   self)
Helper method to get formatted help page for the current
context and command.

◆ get_parameter_source()

ParameterSource | None click.core.Context.get_parameter_source (   self,
str  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 :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.

◆ get_usage()

str click.core.Context.get_usage (   self)
Helper method to get formatted usage string for the current
context and command.

◆ invoke()

t.Any | V click.core.Context.invoke (   self,
Command | t.Callable[..., V]  callback,
*t.Any  args,
**t.Any   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.

.. versionchanged:: 8.0
    All ``kwargs`` are tracked in :attr:`params` so they will be
    passed if :meth:`forward` is called at multiple levels.

.. versionchanged:: 3.2
    A new context is created, and missing arguments use default values.

◆ lookup_default()

t.Any | None click.core.Context.lookup_default (   self,
str  name,
bool   call = True 
)
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.

◆ make_formatter()

HelpFormatter click.core.Context.make_formatter (   self)
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.

◆ meta()

dict[str, t.Any] click.core.Context.meta (   self)
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

◆ scope()

cabc.Iterator[Context] click.core.Context.scope (   self,
bool   cleanup = True 
)
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.

◆ set_parameter_source()

None click.core.Context.set_parameter_source (   self,
str  name,
ParameterSource  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`.

◆ to_info_dict()

dict[str, t.Any] click.core.Context.to_info_dict (   self)
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

◆ with_resource()

V click.core.Context.with_resource (   self,
AbstractContextManager[V]  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 :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

The documentation for this class was generated from the following file: