| 2 | import threading |
| 3 | |
| 4 | class LazyConnection: |
| 5 | def __init__(self, address, family=AF_INET, type=SOCK_STREAM): |
| 6 | self.address = address |
| 7 | self.family = AF_INET |
| 8 | self.type = SOCK_STREAM |
| 9 | self.local = threading.local() |
| 10 | |
| 11 | def __enter__(self): |
| 12 | sock = socket(self.family, self.type) |
| 13 | sock.connect(self.address) |
| 14 | if not hasattr(self.local, 'connections'): |
| 15 | self.local.connections = [] |
| 16 | self.local.connections.append(sock) |
| 17 | return sock |
| 18 | |
| 19 | def __exit__(self, exc_ty, exc_val, tb): |
| 20 | self.local.connections.pop().close() |
| 21 | |
| 22 | def test(conn): |
| 23 | # Example use |