r/Python • • Nov 25 '22

Intermediate Showcase defer in python!

https://github.com/dankeyy/defer.py

stupid but works lol hope you like it

303 Upvotes

62 comments sorted by

View all comments

Show parent comment

12

u/RockingDyno Nov 26 '22

Python essentially has a defer statement and it looks like this:

from contextlib import closing
def my_function(x, y):
    with closing(thing(x)) as X, closing(thing(y)) as Y:
       do_something_with_thing(X)
       do_something_with_thing(Y)

Where the context manager ensures things get closed at the end of the context. Pretty much equivalent to your second code block.