nesting context managers

Rami Chowdhury rami.chowdhury at gmail.com
Tue Dec 20 11:25:58 EST 2011


On Tue, Dec 20, 2011 at 14:15, Ulrich Eckhardt
<ulrich.eckhardt at dominolaser.com> wrote:
> Hi!
>
> Let us assume I had a class HTTPClient that has a socket for HTTP and a
> logfile for filing logs. I want to make this HTTPClient a context manager,
> so that I can write
>
>  with HTTPClient(url) as client:
>      pass
>
> and reliably have both the socket and the logfile closed. The easy way is
> wrong
>
>  def __enter__(self):
>      with self._mysock, self._myfile:
>          return self
>

It seems like some of the functions in the contextlib module might
help? You could try and reorganize your code so that you can use the
@contextmanager decorator, for instance?

That having been said, it doesn't seem that difficult to me to code
your own simple __exit__ method if you're already coding up __enter__
?

HTH,
Rami

-- 
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
+44-7581-430-517 / +1-408-597-7068 / +88-0189-245544



More information about the Python-list mailing list