|
41 | 41 |
|
42 | 42 | # stdlib
|
43 | 43 | import sys
|
| 44 | +from typing import TYPE_CHECKING, ContextManager, Optional, TypeVar |
44 | 45 |
|
45 |
| -__all__ = ["importlib_resources", "importlib_metadata"] |
| 46 | +# this package |
| 47 | +import domdf_python_tools |
| 48 | + |
| 49 | +__all__ = ["importlib_resources", "importlib_metadata", "nullcontext"] |
46 | 50 |
|
47 | 51 | if sys.version_info < (3, 7): # pragma: no cover (>=py37)
|
48 | 52 | # 3rd party
|
|
57 | 61 | else: # pragma: no cover (<py38)
|
58 | 62 | # stdlib
|
59 | 63 | import importlib.metadata as importlib_metadata
|
| 64 | + |
| 65 | +if sys.version_info < (3, 7) or domdf_python_tools.__docs or TYPE_CHECKING: # pragma: no cover (>=py37) |
| 66 | + |
| 67 | + _T = TypeVar("_T") |
| 68 | + |
| 69 | + class nullcontext(ContextManager): |
| 70 | + """ |
| 71 | + Context manager that does no additional processing. |
| 72 | +
|
| 73 | + Used as a stand-in for a normal context manager, when a particular |
| 74 | + block of code is only sometimes used with a normal context manager: |
| 75 | +
|
| 76 | + .. code-block:: python |
| 77 | +
|
| 78 | + cm = optional_cm if condition else nullcontext() |
| 79 | + with cm: |
| 80 | + # Perform operation, using optional_cm if condition is True |
| 81 | +
|
| 82 | + .. versionadded:: 2.1.0 |
| 83 | +
|
| 84 | + :param enter_result: An optional value to return when entering the context. |
| 85 | + """ |
| 86 | + |
| 87 | + # From CPython |
| 88 | + # Licensed under the Python Software Foundation License Version 2. |
| 89 | + # Copyright © 2001-2020 Python Software Foundation. All rights reserved. |
| 90 | + # Copyright © 2000 BeOpen.com. All rights reserved. |
| 91 | + # Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved. |
| 92 | + # Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved. |
| 93 | + |
| 94 | + def __init__(self, enter_result: Optional[_T] = None): |
| 95 | + self.enter_result: Optional[_T] = enter_result |
| 96 | + |
| 97 | + def __enter__(self) -> Optional[_T]: |
| 98 | + return self.enter_result |
| 99 | + |
| 100 | + def __exit__(self, *excinfo): |
| 101 | + pass |
| 102 | + |
| 103 | +else: # pragma: no cover (<py37) |
| 104 | + # stdlib |
| 105 | + from contextlib import nullcontext |
0 commit comments