contextlib.closing annoyance

Klaas mike.klaas at gmail.com
Mon Jun 25 16:26:08 EDT 2007


On Jun 22, 4:54 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> it looks like contextlib.closing fails to be idempotent,
> i.e. wrapping closing() around another closing() doesn't work.

> This is annoying because the idea of closing() is to let you
> use legacy file-like objects as targets of the "with" statement,
> e.g.
>
>     with closing(gzip.open(filename)) as zf: ...
>
> but what happens if the gzip library gets updated the dumb way to
> support the enter and exit methods so you don't need the explicit
> closing call any more?  The dumb way of course is to just call
> closing() inside the library.  It seems to me that
> closing(closing(f)) ought to do the same thing as closing(f).
>
> Let me know if I'm overlooking something.  I'm thinking of submitting
> an RFE.

I'm not sure what "calling closing() inside the library" entails.  In
the __enter__ method?  I don't see how that could work.  Nor anywhere
else, really: an object does not have the ability to wrap itself in a
context manager (without explicitly emulating the functionality by
calling the __-methods).  Indeed, why wouldn't this be the shortest
(and dumbest) implementation?

class gzip.File:
   def __enter__(self):
       return self
   def __exit__(self, *args):
       self.close()

-Mike




More information about the Python-list mailing list