from socket import socket, AF_INET, SOCK_STREAM from functools import partial class ConexionDiferida: def __init__(self, direccion, familia=AF_INET, tipo=SOCK_STREAM): self.direccion = direccion self.familia = AF_INET self.tipo = SOCK_STREAM self.sock = None def __enter__(self): if self.sock is not None: raise Runtimeerror('La conexión ya se ha realizado') self.sock = socket(self.familia, self.tipo) self.sock.connect(self.direccion) return self.sock def __exit__(self, exc_type, exc_val, exc_tb): self.sock.close() self.sock = None if __name__ == '__main__': conexion = ConexionDiferida(('www.python.org', 80)) with conexion as s: # conexion.__enter__() se ejecuta: la conexión se abre s.send(b'GET /index.html HTTP/1.0\r\n') s.send(b'Host: www.python.org\r\n') s.send(b'\r\n') respuesta = b''.join(iter(partial(s.recv, 8192), b'')) # conexion.__exit__() se ejecuta: la conexión se cierra