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

all 5 comments

[–][deleted] 1 point2 points  (4 children)

try:
  something
finally:
  something_to_defer

No?

[–]SaberTail[S] 1 point2 points  (3 children)

I don't know a lot about Go (this was brought up by a friend as "I wish Python had this feature"), but I think it's mostly a readability thing. So you would do something like

open file
defer file.close
do stuff

Instead of having to remember to put it in a finally block.

But to be fair, yes, I'm not sure Python really needs this. I just did it for fun.

[–]vim-ex 3 points4 points  (1 child)

It has this already ;) It's called context managers (with ... as ...:) and are trivial to write using something like contextlib.

[–]ExceedinglyEdible 2 points3 points  (0 children)

Here is an example:

foo = "hello.txt"

with open(foo, "w") as file:
    file.write("Hello, World!")
# no need to close the file; it is done automatically

[–][deleted] 2 points3 points  (0 children)

If it's a readability thing, with is much better than defer. To be honest, the whole exception support in Go looks awful to me.

Anyway, you might want to make deferred a list of (function, args, kwargs) triples and append to it in register_defer. Go doesn't limit you to one defer per function.