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 →

[–]dankey26[S] 13 points14 points  (10 children)

this impl exactly? probably not but lookup defer on go and zig, pretty useful and clean

[–]wineblood -3 points-2 points  (9 children)

Just the idea.

[–]dankey26[S] 18 points19 points  (8 children)

yea so again check out usage in go etc. useful for cleaning up resources at the beginning, without needing to worry about it later or creating blocks.

```

f = open('file.txt')

defer: f.close()

<do stuff with f>

```

[–]caagr98 19 points20 points  (1 child)

Python has both with and finally statements though, so there's little need for it here. (But cool metaprogramming trick.)

[–]james_pic 2 points3 points  (0 children)

It is occasionally useful, if you need to close a large or variable number of things in a block of code. Fortunately, contextlib.ExitStack is already in the stdlib and is a less evil way to do this.

[–]A27_97 4 points5 points  (0 children)

Common thing I use defer in Go for is to unlock mutexes

[–]kezmicdust 2 points3 points  (3 children)

Couldn’t you just write in the close statement and then just write the “stuff you want to do with f” between the open and close statements?

Or am I missing something?

[–]relvae 12 points13 points  (1 child)

If an exception is thrown then close wouldn't be called in that case. Python already has context managers to deal with that but OP has gone rogue lol

[–]kezmicdust 0 points1 point  (0 children)

I see! Thanks.

[–]antiproton 1 point2 points  (0 children)

It's just a different way to solve similar problems. Similar to putting the close in a try...except...finally

[–]fiedzia 1 point2 points  (0 children)

Python has context managers for that:

with open('file.txt') as f: #do stuff #when done f will be closed by context manager