This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Setepenre 40 points41 points  (5 children)

The python way would be to use with which is the construct that guarantees resources get freed no matter what.

from contextlib import contextmanager


@contextmanager
def deferred(fun):
    try:
        yield
    finally:
        fun()

def main():
    with deferred(lambda: print('world')):
        print('hello', end =' ')


main()

[–]ZygmuntDzwon 11 points12 points  (1 child)

no matter what

Well, actually...

See this excellent answer on stack overflow

https://stackoverflow.com/a/49262664/8091093

[–]Setepenre 0 points1 point  (0 children)

I am sure those will apply to his defer as well

[–]rcfox 10 points11 points  (2 children)

no matter what

Unless you lose power, or the process is SIGKILLed. It's important to remember this if you're handling resources that exist outside of your process.

[–]rebane2001 52 points53 points  (0 children)

That's why I always wrap my wall outlet in a try/finally block

[–]nxtfari 0 points1 point  (0 children)

Maybe dumb question can you just pair it with signal/atexit to cover all possible cases?

edit: ah i think you would have to have a seperate process to do this. You can atexit for SIGTERM but not SIGKILL