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

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 

17@t.overload 

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

19 ... 

20 

21 

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. 

28 

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

30 

31 .. versionadded:: 5.0 

32 

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 

42 

43 return None 

44 

45 

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

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

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

49 

50 

51def pop_context() -> None: 

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

53 _local.stack.pop() 

54 

55 

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 

63 

64 ctx = get_current_context(silent=True) 

65 

66 if ctx is not None: 

67 return ctx.color 

68 

69 return None