Coverage for typer / _click / globals.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-11-09 00:15 +0000

1from threading import local 1abcdefg

2from typing import TYPE_CHECKING, Literal, Union, cast, overload 1abcdefg

3 

4if TYPE_CHECKING: 1abcdefg

5 from .core import Context 

6 

7_local = local() 1abcdefg

8 

9 

10@overload 1abcdefg

11def get_current_context(silent: Literal[False] = False) -> "Context": ... 1abcdefg

12 

13 

14@overload 1abcdefg

15def get_current_context(silent: bool = ...) -> Union["Context", None]: ... 1abcdefg

16 

17 

18def get_current_context(silent: bool = False) -> Union["Context", None]: 1abcdefg

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

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

21 alternative to the `pass_context` decorator. This function is 

22 primarily useful for helpers such as `echo` which might be 

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

24 

25 To push the current context, `Context.scope` can be used. 

26 """ 

27 try: 1abcdefg

28 return cast("Context", _local.stack[-1]) 1abcdefg

29 except (AttributeError, IndexError) as e: 1abcdefg

30 if not silent: 1abcdefg

31 raise RuntimeError( 

32 "There is no active click context." 

33 ) from e # pragma: no cover 

34 

35 return None 1abcdefg

36 

37 

38def push_context(ctx: "Context") -> None: 1abcdefg

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

40 _local.__dict__.setdefault("stack", []).append(ctx) 1abcdefg

41 

42 

43def pop_context() -> None: 1abcdefg

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

45 _local.stack.pop() 1abcdefg

46 

47 

48def resolve_color_default(color: bool | None = None) -> bool | None: 1abcdefg

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

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

51 the current context. 

52 """ 

53 if color is not None: 1abcdefg

54 return color 1abcdefg

55 

56 ctx = get_current_context(silent=True) 1abcdefg

57 

58 if ctx is not None: 1abcdefg

59 return ctx.color 1abcdefg

60 

61 return None 1abcdefg