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

Side by Side 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 3 years, 12 months 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 unified diff | 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 »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 # Copyright 2016 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5
6 class _OptionalContextManager(object):
7
8 def __init__(self, manager, condition):
9 self._manager = manager
10 self._condition = condition
11
12 def __enter__(self):
13 if self._condition:
14 return self._manager.__enter__()
15 return None
16
17 def __exit__(self, exc_type, exc_val, exc_tb):
18 if self._condition:
19 return self._manager.__exit__(exc_type, exc_val, exc_tb)
20 return None
21
22
23 def Optional(manager, condition):
24 """Wraps the provided context manager and runs it if condition is True.
25
26 Args:
27 manager: A context manager to conditionally run.
28 condition: If true, runs the given context manager.
29 Returns:
30 A context manager that conditionally executes the given manager.
31 """
32 return _OptionalContextManager(manager, condition)
33
OLDNEW
« 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