Skip to content

Commit e55f97a

Browse files
committed
add contextlib.nullcontext
1 parent e05721c commit e55f97a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

python-stdlib/contextlib/contextlib.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,3 +173,29 @@ def __exit__(self, *exc_details):
173173
if pending_raise:
174174
raise exc_details[1]
175175
return received_exc and suppressed_exc
176+
177+
class nullcontext:
178+
"""Context manager that does no additional processing.
179+
180+
Used as a stand-in for a normal context manager, when a particular
181+
block of code is only sometimes used with a normal context manager:
182+
183+
cm = optional_cm if condition else nullcontext()
184+
with cm:
185+
# Perform operation, using optional_cm if condition is True
186+
"""
187+
188+
def __init__(self, enter_result=None):
189+
self.enter_result = enter_result
190+
191+
def __enter__(self):
192+
return self.enter_result
193+
194+
def __exit__(self, *excinfo):
195+
pass
196+
197+
async def __aenter__(self):
198+
return self.enter_result
199+
200+
async def __aexit__(self, *excinfo):
201+
pass

0 commit comments

Comments
 (0)