Re: Context manager on method call from class

2018-03-15 Thread Joseph L. Casale
From: Python-list <python-list-bounces+jcasale=activenetwerx@python.org> on 
behalf of Rob Gaddi <rgaddi@highlandtechnology.invalid>
Sent: Thursday, March 15, 2018 12:47 PM
To: python-list@python.org
Subject: Re: Context manager on method call from class
    
> 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.

Nice, all of what I wrote replaced with three lines:)

Thank you,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Context manager on method call from class

2018-03-15 Thread Rob Gaddi

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.
--
https://mail.python.org/mailman/listinfo/python-list