-
-
Save anonymous/79f633394374e32a8ddf01bb9238da5f to your computer and use it in GitHub Desktop.
This file contains 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 random # for simulate init fail | |
import contextlib | |
def simulate_init_fail(threshold=50): | |
if random.randint(1, 100) < threshold: | |
print('Init fail') | |
raise RuntimeError('Simulate initialization fail.') | |
print('Init OK') | |
@contextlib.contextmanager | |
def init_process1(): | |
print('This is init_process1') | |
simulate_init_fail(20) | |
try: | |
yield | |
finally: | |
release_process1() | |
@contextlib.contextmanager | |
def init_process2(): | |
print('This is init_process2') | |
simulate_init_fail(40) | |
try: | |
yield | |
finally: | |
release_process2() | |
@contextlib.contextmanager | |
def init_process3(): | |
print('This is init_process3') | |
simulate_init_fail(60) | |
try: | |
yield | |
finally: | |
release_process3() | |
def release_process1(): | |
print('This is release_process1') | |
def release_process2(): | |
print('This is release_process2') | |
def release_process3(): | |
print('This is release_process3') | |
@contextlib.contextmanager | |
def init_phase(): | |
with init_process1(): | |
with init_process2(): | |
with init_process3(): | |
yield | |
def main(): | |
try: | |
with init_phase(): | |
print("Do something...") | |
except Exception as ex: | |
print('Error:', ex) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment