Context manager on method call from class

Rob Gaddi rgaddi at highlandtechnology.invalid
Thu Mar 15 14:47:26 EDT 2018


On 03/15/2018 11:17 AM, Joseph L. Casale wrote:
> I have a class which implements a context manager, its __init__
> has a signature and the __enter__ returns an instance of the
> class.
> 
> Along with several methods which implement functionality on
> the instance, I have one method which itself must open a context
> manager against a call on an instance attribute. This context manager
> does not return an instance of itself, it merely opens a context.
> 
> I am not thrilled about is the implementation I have used and I
> am wondering if there is a better way. It's been a long time since
> I have worked in Python and I am probably overlooking something
> obvious. Syntactically I achieve what I want in use, but it looks awkward
> in its implementation. How can I clean up the first class and decorator
> to implement the functionality on a method in the Foo class?
> 
 > [snip]

from contextlib import contextmanager.

Then you just use the @contextmanager decorator on a function, have it 
set up, yield the context you want, and clean up after.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list