Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/click/globals.py: 46%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

28 statements  

1from __future__ import annotations 

2 

3import typing as t 

4from threading import local 

5 

6if t.TYPE_CHECKING: 

7 from .core import Context 

8 

9_local = local() 

10 

11 

12@t.overload 

13def get_current_context(silent: t.Literal[False] = False) -> Context: ... 

14 

15 

16@t.overload 

17def get_current_context(silent: bool = ...) -> Context | None: ... 

18 

19 

20def get_current_context(silent: bool = False) -> Context | None: 

21 """Returns the current click context. This can be used as a way to 

22 access the current context object from anywhere. This is a more implicit 

23 alternative to the :func:`pass_context` decorator. This function is 

24 primarily useful for helpers such as :func:`echo` which might be 

25 interested in changing its behavior based on the current context. 

26 

27 To push the current context, :meth:`Context.scope` can be used. 

28 

29 .. versionadded:: 5.0 

30 

31 :param silent: if set to `True` the return value is `None` if no context 

32 is available. The default behavior is to raise a 

33 :exc:`RuntimeError`. 

34 """ 

35 try: 

36 return t.cast("Context", _local.stack[-1]) 

37 except (AttributeError, IndexError) as e: 

38 if not silent: 

39 raise RuntimeError("There is no active click context.") from e 

40 

41 return None 

42 

43 

44def push_context(ctx: Context) -> None: 

45 """Pushes a new context to the current stack.""" 

46 _local.__dict__.setdefault("stack", []).append(ctx) 

47 

48 

49def pop_context() -> None: 

50 """Removes the top level from the stack.""" 

51 _local.stack.pop() 

52 

53 

54def resolve_color_default(color: bool | None = None) -> bool | None: 

55 """Internal helper to get the default value of the color flag. If a 

56 value is passed it's returned unchanged, otherwise it's looked up from 

57 the current context. 

58 """ 

59 if color is not None: 

60 return color 

61 

62 ctx = get_current_context(silent=True) 

63 

64 if ctx is not None: 

65 return ctx.color 

66 

67 return None