Skip to content

Instantly share code, notes, and snippets.

@meysampg
Created August 19, 2019 07:43
Show Gist options
  • Save meysampg/11316dc12844a3fdf0862955067e4110 to your computer and use it in GitHub Desktop.
Save meysampg/11316dc12844a3fdf0862955067e4110 to your computer and use it in GitHub Desktop.
from contextlib import ExitStack
from functools import partial
# In some situation it's needed to care about program termination, explicitly or implicitly (by kill or raising an
# exception in the flow), situation likes send a notification on termination. For this purpose we can use contextlib
# of Python. Define our callbacks and put our main in an ExitStack. For more information see
# https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack
def printStars():
print("*********************************")
def someBuggyFunction():
for i in range(5):
print(i)
raise Exception("Hello World")
with ExitStack() as stack:
stack.callback(partial(printStars))
someBuggyFunction()
print("you never see this")
@meysampg
Copy link
Author

meysam@snappmarket:~/www/test/python/callstack 
$ python3 main.py 
0
1
2
3
4
*********************************
Traceback (most recent call last):
  File "main.py", line 24, in <module>
    someBuggyFunction()
  File "main.py", line 18, in someBuggyFunction
    raise Exception("Hello World")
Exception: Hello World

@meysampg
Copy link
Author

meysampg commented Sep 5, 2019

I really miss the defer of GO in python 😢.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment