Coverage for src / zmqtt / _internal / _compat.py: 41%

49 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-11-12 08:49 +0000

1"""Python version compatibility helpers.""" 

2 

3import asyncio 

4import contextlib 

5import sys 

6from collections.abc import AsyncGenerator, Awaitable 

7from typing import Any, TypeVar 

8 

9if sys.version_info >= (3, 11): 

10 from typing import Self 

11else: 

12 from typing_extensions import Self 

13 

14__all__ = ("Self", "defer_cancellation", "wait_for") 

15 

16_T = TypeVar("_T") 

17 

18if sys.version_info >= (3, 12): 

19 wait_for = asyncio.wait_for # noqa: TID251 - fixed in 3.12 (python/cpython#96764) 

20 

21else: 

22 

23 async def wait_for(aw: Awaitable[_T], timeout: float | None) -> _T: 

24 """``asyncio.wait_for()`` that never hides a cancellation. 

25 

26 Before 3.12, ``asyncio.wait_for()`` returns the result instead of 

27 raising ``CancelledError`` when the awaited task has already finished 

28 by the time the cancellation is handled (python/cpython#86296). 

29 """ 

30 if timeout is None: 

31 return await aw 

32 task = asyncio.ensure_future(aw) 

33 try: 

34 await asyncio.wait((task,), timeout=timeout) 

35 except asyncio.CancelledError: 

36 await _cancel_and_wait(task) 

37 raise 

38 if task.done(): 

39 return task.result() 

40 await _cancel_and_wait(task) 

41 try: 

42 return task.result() 

43 except asyncio.CancelledError as e: 

44 raise asyncio.TimeoutError from e 

45 

46 async def _cancel_and_wait(task: asyncio.Future[Any]) -> None: 

47 task.cancel() 

48 await asyncio.wait((task,)) 

49 if not task.cancelled(): 

50 task.exception() # mark retrieved: the caller reports its own outcome 

51 

52 

53if sys.version_info >= (3, 11): 

54 

55 @contextlib.asynccontextmanager 

56 async def defer_cancellation() -> AsyncGenerator[None, None]: 

57 """Temporarily remove pending cancellations, restore them after cleanup.""" 

58 task = asyncio.current_task() 

59 cancels = task.cancelling() if task else 0 

60 for _ in range(cancels): 

61 if task: 

62 task.uncancel() 

63 try: 

64 yield 

65 finally: 

66 for _ in range(cancels): 

67 if task: 

68 task.cancel() 

69 

70else: 

71 

72 @contextlib.asynccontextmanager 

73 async def defer_cancellation() -> AsyncGenerator[None, None]: 

74 """No-op on Python < 3.11: cancelling()/uncancel() are not available.""" 

75 yield