contextlib.closing annoyance

P

Paul Rubin

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.
 
K

Klaas

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top