Skip to content

Commit 91b0e22

Browse files
committed
Add nullcontext for Python 3.6
1 parent 22826ec commit 91b0e22

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

doc-source/api/compat.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
=================================
44

55
.. automodule:: domdf_python_tools.compat
6-
:no-members:
6+
:no-autosummary:
7+
:no-special-members:

domdf_python_tools/compat.py

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,12 @@
4141

4242
# stdlib
4343
import sys
44+
from typing import TYPE_CHECKING, ContextManager, Optional, TypeVar
4445

45-
__all__ = ["importlib_resources", "importlib_metadata"]
46+
# this package
47+
import domdf_python_tools
48+
49+
__all__ = ["importlib_resources", "importlib_metadata", "nullcontext"]
4650

4751
if sys.version_info < (3, 7): # pragma: no cover (>=py37)
4852
# 3rd party
@@ -57,3 +61,45 @@
5761
else: # pragma: no cover (<py38)
5862
# stdlib
5963
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

Comments
 (0)