Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #17588

Re: nesting context managers

References <ash6s8-qj5.ln1@satorlaser.homedns.org>
Date 2011-12-20 16:25 +0000
Subject Re: nesting context managers
From Rami Chowdhury <rami.chowdhury@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.3868.1324398361.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Tue, Dec 20, 2011 at 14:15, Ulrich Eckhardt
<ulrich.eckhardt@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

nesting context managers Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2011-12-20 15:15 +0100
  Re: nesting context managers Rami Chowdhury <rami.chowdhury@gmail.com> - 2011-12-20 16:25 +0000
  Re: nesting context managers Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2011-12-20 17:56 +0100
    Re: nesting context managers Rami Chowdhury <rami.chowdhury@gmail.com> - 2011-12-20 17:46 +0000
    Re: nesting context managers Ian Kelly <ian.g.kelly@gmail.com> - 2011-12-20 11:46 -0700
    Re: nesting context managers Ethan Furman <ethan@stoneleaf.us> - 2011-12-20 10:02 -0800
    Re: nesting context managers Ian Kelly <ian.g.kelly@gmail.com> - 2011-12-20 11:55 -0700

csiph-web