python-click/src/click/globals.py

48 lines
1.5 KiB
Python
Raw Normal View History

2015-08-23 03:10:31 +02:00
from threading import local
_local = local()
def get_current_context(silent=False):
"""Returns the current click context. This can be used as a way to
access the current context object from anywhere. This is a more implicit
alternative to the :func:`pass_context` decorator. This function is
primarily useful for helpers such as :func:`echo` which might be
2018-09-06 20:55:10 +02:00
interested in changing its behavior based on the current context.
2015-08-23 03:10:31 +02:00
To push the current context, :meth:`Context.scope` can be used.
.. versionadded:: 5.0
2020-07-21 08:23:42 +02:00
:param silent: if set to `True` the return value is `None` if no context
2015-08-23 03:10:31 +02:00
is available. The default behavior is to raise a
:exc:`RuntimeError`.
"""
try:
2020-07-21 08:23:42 +02:00
return _local.stack[-1]
2015-08-23 03:10:31 +02:00
except (AttributeError, IndexError):
if not silent:
2020-07-21 08:23:42 +02:00
raise RuntimeError("There is no active click context.")
2015-08-23 03:10:31 +02:00
def push_context(ctx):
"""Pushes a new context to the current stack."""
2020-07-21 08:23:42 +02:00
_local.__dict__.setdefault("stack", []).append(ctx)
2015-08-23 03:10:31 +02:00
def pop_context():
"""Removes the top level from the stack."""
_local.stack.pop()
def resolve_color_default(color=None):
""""Internal helper to get the default value of the color flag. If a
value is passed it's returned unchanged, otherwise it's looked up from
the current context.
"""
if color is not None:
return color
ctx = get_current_context(silent=True)
if ctx is not None:
return ctx.color