Context manager to save/restore a name binding

Chris Withers chris at python.org
Fri Aug 31 07:06:04 EDT 2012


Hi Ben,

On 31/08/2012 03:36, Ben Finney wrote:
> That way, I can set ‘sys.dont_write_bytecode’ to the value I need in
> this part of the code, knowing that however the code continues the
> previous value of that setting will be restored to whatever it was
> before I touched it.
>
> Have I re-invented a context manager which already exists? Is there a
> better way to do what ‘preserve_value’ is doing?

Depends on the context (ho ho..), but if it's testing, then have a look at:

http://packages.python.org/testfixtures/mocking.html#the-context-manager

There's plenty of other goodies you may like in there too...

cheers,

Chris

-- 
Simplistix - Content Management, Batch Processing & Python Consulting
             - http://www.simplistix.co.uk



More information about the Python-list mailing list