Coverage for python / lsst / pipe / base / log_on_close.py: 59%

17 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-13 01:30 -0800

1# This file is part of pipe_base. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

15# This program is free software: you can redistribute it and/or modify 

16# it under the terms of the GNU General Public License as published by 

17# the Free Software Foundation, either version 3 of the License, or 

18# (at your option) any later version. 

19# 

20# This program is distributed in the hope that it will be useful, 

21# but WITHOUT ANY WARRANTY; without even the implied warranty of 

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

25# You should have received a copy of the GNU General Public License 

26# along with this program. If not, see <http://www.gnu.org/licenses/>. 

27 

28from __future__ import annotations 

29 

30__all__ = ("LogOnClose",) 

31 

32from collections.abc import Callable, Iterator 

33from contextlib import AbstractContextManager, contextmanager 

34from typing import TypeVar 

35 

36from lsst.utils.logging import VERBOSE 

37 

38_T = TypeVar("_T") 

39 

40 

41class LogOnClose: 

42 """A factory for context manager wrappers that emit a log message when 

43 they are closed. 

44 

45 Parameters 

46 ---------- 

47 log_func : `~collections.abc.Callable` [ `int`, `str` ] 

48 Callable that takes an integer log level and a string message and emits 

49 a log message. Note that placeholder formatting is not supported. 

50 """ 

51 

52 def __init__(self, log_func: Callable[[int, str], None]): 

53 self.log_func = log_func 

54 

55 def wrap( 

56 self, 

57 cm: AbstractContextManager[_T], 

58 msg: str, 

59 level: int = VERBOSE, 

60 ) -> AbstractContextManager[_T]: 

61 """Wrap a context manager to log when it is exited. 

62 

63 Parameters 

64 ---------- 

65 cm : `contextlib.AbstractContextManager` 

66 Context manager to wrap. 

67 msg : `str` 

68 Log message. 

69 level : `int`, optional 

70 Log level. 

71 """ 

72 

73 @contextmanager 

74 def wrapper() -> Iterator[_T]: 

75 with cm as result: 

76 yield result 

77 self.log_func(level, msg) 

78 

79 return wrapper()