Re:Implementing Go's defer keyword in C++
by lstyls on Saturday October 21, 2017 @08:13PM
(#15524363)
I know Python far better than Ruby, but it looks like the semantics are equivalent, it's just that Ruby's standard `open` implementation includes the cleanup rather than leaving it up to the caller as in Python.
Re:Implementing Go's defer keyword in C++
by masklinn on Sunday October 22, 2017 @06:23AM
(#15526032)
One difference is that Ruby does not need a special language construct/protocol to do so.
An other is that Python's "context managers" are reified which means you can pass them around until you ultimately use them. It's a tradeoff.
Re:Implementing Go's defer keyword in C++
by int_19h on Saturday October 21, 2017 @10:56PM
(#15524919)
Ruby does this at the cost of having non-local returns from those blocks, which complicates semantics quite a bit (since now you need to distinguish closures that capture "return" and other control transfer from those that don't, and you need to handle the scenario where a control transfer happens when the target is already gone).
Re:Implementing Go's defer keyword in C++
by asdfaoeu on Sunday October 22, 2017 @02:11AM
(#15525414)
You can do basically the same thing in python
@contextlib.contextmanager
def open(*args)
# file open
try:
yield file
finally:
file.close()
with open(args) as file:
# use fileThat's pretty cool!
But as nice as it is, to me it's just syntax sugar over the wrong abstraction instead of something beautiful in it's own right.
Re:Implementing Go's defer keyword in C++
by masklinn on Sunday October 22, 2017 @06:24AM
(#15526037)
On the other hand, it means any helper/builder has to handle this pattern on its own rather than be able to return a file object which can be "context managed" by a caller, which Python allows.
True, but it's fairly easy to write:
def self.open
File.open(...) { |f| yield f }
end
Unless they need custom destructor actions, in which case presumably they'd have to implement that manually in python too.
For example
And the implementation is simply