Skip to content

Instantly share code, notes, and snippets.

@romuald
Created April 28, 2020 14:09
Show Gist options
  • Save romuald/80011a54c501ca624a577c2878bb4220 to your computer and use it in GitHub Desktop.
Save romuald/80011a54c501ca624a577c2878bb4220 to your computer and use it in GitHub Desktop.
Proof of concept for a python equivalent of golang's defer statement
import os
import inspect
class defer:
"""
Proof of concept for a python equivalent of golang's defer statement
Note that the callback order is probably not guaranteed
"""
def __init__(self, callback, *args, **kwargs):
self.callback = callback
self.args = args
self.kwargs = kwargs
# Add a reference to self in the caller variables so our __del__
# method will be called when the function goes out of scope
caller = inspect.currentframe().f_back
caller.f_locals[b'_' + os.urandom(48)] = self
def __del__(self):
self.callback(*self.args, **self.kwargs)
def first():
print('- first')
defer(lambda: print(' - deferred'))
print('- first exit')
def second():
print('- second')
def main():
first()
second()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment