Defer is an awesome control flow construct. Python implementations have historically relied on cumbersome decorators or other manual coordination. No more!
Use python-defer
to schedule code to be run at the end of a function, whether or not anything fails. Think of it like an automagic finally
block that you can use inline anywhere.
Check out the blog post to learn how this was built.
$ pip install python-defer
The default way to use python-defer
is true magic. Simply write your code and append an in defer
to it.
from defer import defer
def foo():
print(", world!") in defer
print("Hello", end="")
# do something that might fail...
assert 1 + 1 == 3
$ python foo.py
Hello, World!
Traceback (most recent call last):
File "foo.py", line 7, in <module>
assert 1 + 1 == 3
AssertionError
If you prefer a more explicit approach, you can use the d
function, which takes a lambda
.
from defer.sugarfree import defer as d
def foo():
d(print, "1")
print("2")
d(lambda: print("3"))
raise RuntimeError("oh no!")
print("4")
$ python foo.py
2
3
1
Traceback (most recent call last):
File "foo.py", line 7, in <module>
RuntimeError: oh no!