0

I was wondering if it was possible to use the with statement conditionally, like

if condition:
    with mock.patch(....)
#code that is or is not patched

Is it theoretically possible to achieve this without losing the with statement?

  • It's not clear what you're trying to achieve here. Please create a more comprehensive example that shows the desired behavior. – Him Dec 04 '19 at 17:44
  • What do you mean by losing the `with` statement? – bereal Dec 04 '19 at 17:45
  • 1
    Does this answer your question? [Conditional with statement in Python](https://stackoverflow.com/questions/27803059/conditional-with-statement-in-python) – alexisdevarennes Dec 04 '19 at 17:45
  • I assume that you want with to apply to the code below the comment if condition is met. There may be a better way to do so - please share a longer piece of code so we'd see the context. – Poe Dator Dec 04 '19 at 17:48

1 Answers1

0

You can create a wrapper context manager that calls the wrapped context manager's __enter__ and __exit__ methods based on the given condition:

class conditional_context_manager:
    def __init__(self, condition, context_manager):
        self.condition = condition
        self.context_manager = context_manager

    def __enter__(self):
        return self.context_manager.__enter__() if self.condition else self

    def __exit__(self, *args, **kwargs):
        if self.condition:
            return self.context_manager.__exit__(*args, **kwargs)

so that:

with conditional_context_manager(False, mock.patch('builtins.print')):
    print('hi')

outputs:

hi

while:

with conditional_context_manager(True, mock.patch('builtins.print')):
    print('hi')

outputs nothing.

Alternatively, you can use a mock.MaigicMock object as a context manager if the condition is not met:

with mock.patch('builtins.print') if condition else mock.MagicMock():
    #code that is or is not patched
blhsing
  • 91,368
  • 6
  • 71
  • 106