-
-
Save anonymous/de1627504251f44dd4dfb831d9f8cadd 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') | |
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