Skip to content

Instantly share code, notes, and snippets.

/with_init.py Secret

Created October 19, 2017 10:23
Show Gist options
  • Save anonymous/79f633394374e32a8ddf01bb9238da5f to your computer and use it in GitHub Desktop.
Save anonymous/79f633394374e32a8ddf01bb9238da5f to your computer and use it in GitHub Desktop.
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