This script defines a "decorator" that, rather than decorating the function, calls it, passing it a file object that it had opened as the first argument.
Of course, it makes sure to close the file upon the function's return (or nonreturn) with a try...finally block. One can use this decorator to get the effect of a Lisp-like with_open_file block in Python.
In Common Lisp, there is a very convenient macro called with-open-file that opens a file, binds the file object to a block-local variable, and then executes the block. The file is automatically closed when that block is exited.
Not having macros in Python, we generally do this with a try...finally statement, which works fine.
But let's try to (ab)use decorators to get a with-open-file block anyways. The call_with_open_file decorator kind of gives us this effect: the decorated function acts as a code block. However, unlike try...finally, it has the limitations of nested functions, so unfortunately this recipe is not quite so useful as the Lisp macro.
Nevertheless, it might stil be useful in the occasional sitation where you have to use libraries that don't let you create and finalize objects yourself, but force you to use a callback. Having no way to use a try...finally, and needing to reference (but hopefully not rebind) local variables, a decorator like the one in this recipe could help.
Top 4 Download periodically updates information of Decorator 1.2 script from the developer, but some information may be slightly out-of-date.
Our script download links are directly from our mirrors or publisher's website. Decorator 1.2 torrent files or shared files from free file sharing and free upload services, including Rapidshare, MegaUpload, YouSendIt, MailBigFile, DropSend, HellShare, HotFile, FileServe, MediaMax, zUpload, MyOtherDrive, SendSpace, DepositFiles, Letitbit, LeapFile, DivShare or MediaFire, are not allowed!