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


Groups > comp.lang.python > #17601

Re: nesting context managers

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!news.stack.nl!newsfeed.xs4all.nl!newsfeed5.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail
Return-Path <ian.g.kelly@gmail.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'context': 0.04; 'socket': 0.04; 'stuff,': 0.07; 'python': 0.08; 'client:': 0.09; 'created,': 0.09; 'deprecated': 0.09; 'finally:': 0.09; 'flush': 0.09; 'garbage': 0.09; 'sockets': 0.09; 'am,': 0.12; 'def': 0.13; '2.7': 0.13; '3.2.': 0.16; 'allocate': 0.16; 'close(self):': 0.16; 'eckhardt': 0.16; 'exc_type,': 0.16; 'exc_value,': 0.16; 'task:': 0.16; '\xa0def': 0.16; 'cc:addr:python-list': 0.16; 'received:74.125.82.44': 0.16; 'received:mail-ww0-f44.google.com': 0.16; 'this:': 0.16; 'wrote:': 0.18; '>>>': 0.18; 'wrap': 0.18; 'file,': 0.19; 'cc:no real name:2**0': 0.20; 'cheers,': 0.20; 'dec': 0.22; 'assume': 0.22; 'header:In-Reply-To:1': 0.22; 'versions': 0.23; 'filing': 0.23; 'itself,': 0.23; 'somehow': 0.23; 'cc:2**0': 0.24; 'code': 0.25; 'ignore': 0.26; 'skip:_ 20': 0.26; 'expect': 0.26; 'function': 0.27; 'fact': 0.27; 'message- id:@mail.gmail.com': 0.28; 'allocated': 0.29; 'assuming': 0.29; 'explicitly': 0.29; 'yield': 0.29; 'cc:addr:python.org': 0.29; 'error': 0.29; 'class': 0.29; 'closing': 0.30; "client's": 0.30; 'email name:': 0.30; 'implicitly': 0.30; 'invoke': 0.30; 'kelly': 0.30; 'remains': 0.30; 'syntax,': 0.30; 'usable': 0.30; "i'll": 0.31; 'does': 0.32; 'attach': 0.32; 'tue,': 0.32; "can't": 0.32; 'normally': 0.34; 'function.': 0.34; 'nested': 0.34; 'try:': 0.34; 'received:74.125.82': 0.35; 'something': 0.35; 'file': 0.36; '...': 0.36; 'http': 0.37; 'but': 0.37; 'received:74.125': 0.37; 'received:google.com': 0.37; 'skip:_ 10': 0.37; 'could': 0.37; 'open': 0.38; 'fail': 0.39; 'skip:\xa0 10': 0.39; 'client': 0.39; "i'd": 0.39; 'files': 0.39; "it's": 0.40; '8bit%:8': 0.40; 'more': 0.61; '2011': 0.61; 'connect': 0.62; 'full': 0.62; 'manager,': 0.62; 'opened': 0.64; 'safe': 0.70; 'completion': 0.82; '11:46': 0.84; 'on-demand': 0.91; 'open,': 0.91
DKIM-Signature v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=mime-version:in-reply-to:references:from:date:message-id:subject:to :cc:content-type:content-transfer-encoding; bh=zV3LVLNmNPxAhJSDiplWjxoDfiJYGiXxvg1zzLxtDYI=; b=n5LRgPpiJyBhdoy90tN844Ryb88Oa6+gjCph4exGZfeZWWBxcM0INB093AIMXVZ+lN QtJLWBPkXTvSU3Iw+It0Q5Q1MLfi8T16/HF/R8hTV8uqtZbTKyETdIX0GrVRcaZZ5Crk IvC46NrTrYLCv0BkYHfIBCnWRb5qN66nlVqAg=
MIME-Version 1.0
In-Reply-To <CALwzidnGdNhfCAiGSAzU6bASCRdof_VGZAL_MCzGx0+dFUKb4A@mail.gmail.com>
References <ash6s8-qj5.ln1@satorlaser.homedns.org> <nbr6s8-n86.ln1@satorlaser.homedns.org> <CALwzidnGdNhfCAiGSAzU6bASCRdof_VGZAL_MCzGx0+dFUKb4A@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date Tue, 20 Dec 2011 11:55:59 -0700
Subject Re: nesting context managers
To Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com>
Content-Type text/plain; charset=ISO-8859-1
Content-Transfer-Encoding quoted-printable
Cc python-list@python.org
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.12
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.3875.1324407391.27778.python-list@python.org> (permalink)
Lines 78
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1324407391 news.xs4all.nl 6981 [2001:888:2000:d::a6]:58601
X-Complaints-To abuse@xs4all.nl
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:17601

Show key headers only | View raw


On Tue, Dec 20, 2011 at 11:46 AM, Ian Kelly <ian.g.kelly@gmail.com> wrote:
> On Tue, Dec 20, 2011 at 9:56 AM, Ulrich Eckhardt
> <ulrich.eckhardt@dominolaser.com> wrote:
>> Am 20.12.2011 15:15, schrieb Ulrich Eckhardt:
>>
>>> 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
>>
>>
>> Actually, I overestimated the task:
>>
>>  class HTTPClient(url):
>>      def __enter__(self):
>>          return self
>>      def __exit__(self, ctx_type, ctx_val, ctx_tb):
>>          self.close()
>>      def close(self):
>>          self._myfile.close()
>>          self._mysocket.close()
>>
>> I'll simply ignore the fact that closing a file can fail if you can't flush
>> buffers. Now, my error was that I have to somehow invoke the file's and
>> socket's enter function in my client's enter function. The default for all
>> files and sockets is that they are already open, they are not opened in the
>> enter function! That way, the client remains usable outside a with context
>> but gives me the desired guarantees inside one.
>>
>> For the case of on-demand allocated stuff, I could write the enter function
>> like this:
>>
>>  def __enter__(self):
>>      # allocate resources
>>      f = ... # open file
>>      s = ... # connect socket
>>      # attach after completion
>>      self._myfile = f
>>      self._mysocket = s
>>
>> To be extra safe or in more complicated scenarios, I could wrap this in a
>> try-except and explicitly close those that were already created, but
>> normally I'd expect the garbage collector to do that for me ... or am I then
>> implicitly assuming a specific implementation?
>
> For full generality, copy the code for the contextlib.nested function
> in Python 2.7 or 3.1 and use that.  Don't use contextlib.nested
> itself, though, because it's deprecated and does not exist in Python
> 3.2.

Also note that in versions that do support the nested with syntax, you
can do something like:

class HTTPClient(url):
    @contextlib.contextmanager
    def _contextmanager(file, socket):
        with file, socket:
            yield
    def __enter__(self):
        self._cm = self._contextmanager(self._myfile, self._mysocket)
        return self._cm.__enter__()
    def __exit__(self, exc_type, exc_value, traceback):
        try:
            return self._cm.__exit__(exc_type, exc_value, traceback)
        finally:
            del self._cm

Cheers,
Ian

Back to comp.lang.python | Previous | NextPrevious 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