Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(16)

Unified Diff: common/py_utils/py_utils/contextlib_ext.py

Issue 2585763004: [py_utils] Add empty and optional context managers. (Closed)
Patch Set: rnephew comment Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | common/py_utils/py_utils/contextlib_ext_unittest.py » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: common/py_utils/py_utils/contextlib_ext.py
diff --git a/common/py_utils/py_utils/contextlib_ext.py b/common/py_utils/py_utils/contextlib_ext.py
new file mode 100644
index 0000000000000000000000000000000000000000..922d27d548b3456d9411190a4c3eddd11c89909a
--- /dev/null
+++ b/common/py_utils/py_utils/contextlib_ext.py
@@ -0,0 +1,33 @@
+# Copyright 2016 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+
+class _OptionalContextManager(object):
+
+ def __init__(self, manager, condition):
+ self._manager = manager
+ self._condition = condition
+
+ def __enter__(self):
+ if self._condition:
+ return self._manager.__enter__()
+ return None
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if self._condition:
+ return self._manager.__exit__(exc_type, exc_val, exc_tb)
+ return None
+
+
+def Optional(manager, condition):
+ """Wraps the provided context manager and runs it if condition is True.
+
+ Args:
+ manager: A context manager to conditionally run.
+ condition: If true, runs the given context manager.
+ Returns:
+ A context manager that conditionally executes the given manager.
+ """
+ return _OptionalContextManager(manager, condition)
+
« no previous file with comments | « no previous file | common/py_utils/py_utils/contextlib_ext_unittest.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698