Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/click/globals.py: 43%
30 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-09 06:03 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-09 06:03 +0000
1from __future__ import annotations
3import typing as t
4from threading import local
6if t.TYPE_CHECKING:
7 from .core import Context
9_local = local()
12@t.overload
13def get_current_context(silent: t.Literal[False] = False) -> Context:
14 ...
17@t.overload
18def get_current_context(silent: bool = ...) -> Context | None:
19 ...
22def get_current_context(silent: bool = False) -> Context | None:
23 """Returns the current click context. This can be used as a way to
24 access the current context object from anywhere. This is a more implicit
25 alternative to the :func:`pass_context` decorator. This function is
26 primarily useful for helpers such as :func:`echo` which might be
27 interested in changing its behavior based on the current context.
29 To push the current context, :meth:`Context.scope` can be used.
31 .. versionadded:: 5.0
33 :param silent: if set to `True` the return value is `None` if no context
34 is available. The default behavior is to raise a
35 :exc:`RuntimeError`.
36 """
37 try:
38 return t.cast("Context", _local.stack[-1])
39 except (AttributeError, IndexError) as e:
40 if not silent:
41 raise RuntimeError("There is no active click context.") from e
43 return None
46def push_context(ctx: Context) -> None:
47 """Pushes a new context to the current stack."""
48 _local.__dict__.setdefault("stack", []).append(ctx)
51def pop_context() -> None:
52 """Removes the top level from the stack."""
53 _local.stack.pop()
56def resolve_color_default(color: bool | None = None) -> bool | None:
57 """Internal helper to get the default value of the color flag. If a
58 value is passed it's returned unchanged, otherwise it's looked up from
59 the current context.
60 """
61 if color is not None:
62 return color
64 ctx = get_current_context(silent=True)
66 if ctx is not None:
67 return ctx.color
69 return None