Skip to content

Instantly share code, notes, and snippets.

/with_init_es.py Secret

Created October 20, 2017 04:20
Show Gist options
  • Save anonymous/de1627504251f44dd4dfb831d9f8cadd to your computer and use it in GitHub Desktop.
Save anonymous/de1627504251f44dd4dfb831d9f8cadd 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')
def init_process1():
print('This is init_process1')
simulate_init_fail(20)
def init_process2():
print('This is init_process2')
simulate_init_fail(40)
def init_process3():
print('This is init_process3')
simulate_init_fail(60)
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 contextlib.ExitStack() as stack:
init_process1()
stack.callback(release_process1)
init_process2()
stack.callback(release_process2)
init_process3()
stack.callback(release_process3)
yield
def init_phase_no_release_if_success():
with contextlib.ExitStack() as stack:
init_process1()
stack.callback(release_process1)
init_process2()
stack.callback(release_process2)
init_process3()
stack.callback(release_process3)
# Initialize other things here...
# ...
stack.pop_all()
def main():
try:
with init_phase():
print('Do something...')
# Another solution that will not invoke release if init success.
#init_phase_no_release_if_success()
#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