[Python-Dev] Creating APIs that work as both decorators and context managers

Mark Dickinson dickinsm at gmail.com
Fri Jun 25 22:02:36 CEST 2010


On Fri, Jun 25, 2010 at 7:35 PM, Michael Foord
<fuzzyman at voidspace.org.uk> wrote:
> Hello all,
>
> I've put a recipe up on the Python cookbook for creating APIs that work as
> both decorators and context managers and wonder if it would be considered a
> useful addition to the functools module.
> http://code.activestate.com/recipes/577273-decorator-and-context-manager-from-a-single-api/

It's an interesting idea.  I wanted almost exactly this a little while
ago, while doing some experiments to add an IEEE 754-compliance
wrapper to the decimal module (for my own use).  It seems quite
natural that one might want to wrap both functions and blocks in the
same way.

[1] In case anyone wants the details, this was for a
'delay-exceptions' operation, that allows you to execute some number
of arithmetic operations, keeping track of the floating-point signals
that they produce but not raising the corresponding exceptions until
the end of the block;  obviously this idea applies equally well to
functions as to blocks.  It's one of the recommended exception
handling modes from section 8 of IEEE 754-2008.

Mark


More information about the Python-Dev mailing list