Skip to content
Advertisement

Conditional or optional context managers in with statement

Suppose I have some kind of context manager (from a third-party library) that I am using like so:

JavaScript

But, suppose if there is no value for test_dt, the context manager should not run, but all of the remaining code should run, like so:

JavaScript

Assume that lines_of_code here is 2-3 lines of code which are exactly identical, is there a cleaner way of writing this? I’m aware that I could write something like this:

JavaScript

But I’m not crazy about this formatting. Also, I don’t want to have to litter this pattern all over my code.

There is one final possibility, but I’m not certain it will work: subclassing the context manager and skipping the __enter__ and __exit__ functions if the test_dt given is empty, like so:

JavaScript

I tested it out with a blank context manager class, and it seemed to behave correctly. However, I’m worried whether a real context manager will behave correctly if I do this (I’m not very familiar with the internals of how it works).

Advertisement

Answer

Here’s an easy way to wrap around an existing context manager without even using any classes:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement