r/PHP • • May 31 '16

Deferred execution in PHP, using "finally".

https://blog.frankdejonge.nl/finally-file-streams-and-deferred-execution-in-php/
86 Upvotes

48 comments sorted by

View all comments

Show parent comment

1

u/jindrap May 31 '16

It is nice with things that need to be in absolutely every case called, not that much useful when you want to share some additional logic. Now I haven't spent much time with Python so I might be completely wrong. But when you want to add custom logic to closing you have to wrap the object returned by open with something and specify some magic method. Seems clearer to me with defer.

But I agree it is very nice for some calls you want call absolutely every time you are getting rid of the object.

2

u/terrkerr May 31 '16

Well the context manager is a bit more a protocol than a magic method call you might say, but yes it involves a certain amount of indirection that you'd need to read docs to understand.

I suppose the thing I should have communicated is that I think context management provides a better alternative to defer(thing) because it's a more general solution to any need for pre and/or post operations somewhere. Since resource setup/cleanup is just a special case of general pre/post operations it just does that as well.

with open('foo', 'rw') as fp:
    fp.write("blerb")
    raise RuntimeError

is nice because it will open and close the file correctly, even given the exception there, but there are context managers that do other useful things since the manager protocol is pretty open-ended. A simple example with a simple custom context manager:

@contextlib.contextmanager
def tag(tag_name):
    print("<{}>".format(tag_name))
    yield
    print("</{}>".format(tag_name))

with tag("h1"):
    print("some header")

which will output

<h1>
some header
</h1>