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 6class _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 23def 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 34