nesting context managers

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Tue Dec 20 09:15:06 EST 2011


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

because it closes the file and socket as part of the return statement. 
Of course I can go the hard way, code everything myself, but I wonder if 
there isn't some useful tool that would help me achieve this (common?) task.

Thanks!

Uli



More information about the Python-list mailing list