LWN.net Logo

PyCon: Evangelizing Python

PyCon: Evangelizing Python

Posted Apr 1, 2013 18:16 UTC (Mon) by nybble41 (subscriber, #55106)
In reply to: PyCon: Evangelizing Python by kleptog
Parent article: PyCon: Evangelizing Python

In Common Lisp the form is known as "unwind-protect" [1], and in Scheme it's "dynamic-wind" [2]. The latter is more complicated because it attempts to handle the case where the inner code is re-entered through a continuation after the cleanup code has already been executed, but the idea is similar.

Both expressions execute a block of code with a guarantee that some other code will be executed when control leaves the block, no matter how that happens (e.g. normal exit, exception, calling a continuation). Operations built on top of this mechanism often start with "with-" by convention, e.g. "with-open-file" (Common Lisp) and "call-with-input-file" (Scheme) both ensure that the file provided to the inner block is closed afterward.

[1] http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node96.html
[2] http://www.schemers.org/Documents/Standards/R5RS/HTML/r5r...


(Log in to post comments)

PyCon: Evangelizing Python

Posted Apr 1, 2013 22:57 UTC (Mon) by nix (subscriber, #2304) [Link]

Needless to say, nothing remotely as complicated as the protocols needed in Python to implement 'with' are needed in Lisp. The macro system and unwind-protect/dynamic-wind provides all you need, and implementing new with-*'s is a matter of a few lines of extremely not difficult code. (I emphasise this because macros can often be extremely arcane. Writing a with-blah isn't one of those: the most you have to worry about is a bit of variable capture.)

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds