Last active
September 6, 2017 18:22
-
-
Save cthoyt/48796cf21687d5a76531035067c809cf to your computer and use it in GitHub Desktop.
A context manager using frame hacks to only run when truthy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import unittest | |
from contextlib import contextmanager | |
# see https://stackoverflow.com/questions/12594148/skipping-execution-of-with-block | |
@contextmanager | |
def when_truthy(argument): | |
""" | |
The point of this function is to make it so you never have to write | |
>>> x = my_function() | |
>>> if x is not None: | |
>>> my_other_function(x) | |
by writing: | |
>>> with when_truthy(my_function()) as x: | |
>>> my_other_function(x) | |
""" | |
if not argument: | |
yield None | |
else: | |
yield argument | |
class Tests(unittest.TestCase): | |
def test_1(self): | |
"""Don't run the inner code if the argument is Falsy""" | |
with my_thing(None) as f: | |
raise ValueError | |
def test_2(self): | |
"""Run the inner code if the argument is not Falsy and keep the argument""" | |
with my_thing(5) as f: | |
assert f == 5 | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment