Coverage for src/minihtml/_context.py: 92%

24 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-04-06 18:07 +0200

1import sys 

2from contextvars import ContextVar 

3from typing import Any 

4 

5if sys.version_info >= (3, 11): 5 ↛ 8line 5 didn't jump to line 8 because the condition on line 5 was always true

6 from typing import Self 

7else: 

8 from typing_extensions import Self 

9 

10 

11_context = ContextVar[dict[type, list[Any]]]("context") 

12 

13 

14class Context: 

15 """ 

16 Base class for context objects. 

17 

18 Implements the context manager protocol. When the context is entered, the current 

19 """ 

20 

21 def _push(self) -> None: 

22 try: 

23 g = _context.get() 

24 except LookupError: 

25 g: dict[type, list[Any]] = {} 

26 _context.set(g) 

27 g.setdefault(type(self), []).append(self) 

28 

29 def _pop(self) -> None: 

30 _context.get()[type(self)].pop() 

31 

32 def __enter__(self) -> None: 

33 self._push() 

34 

35 def __exit__(self, *exc_info: object) -> None: 

36 self._pop() 

37 

38 @classmethod 

39 def get(cls) -> Self: 

40 """ 

41 Get the current instance of the context object. 

42 """ 

43 return _context.get()[cls][-1]