MCPcopy Create free account
hub / github.com/dabeaz/python-cookbook / LazyConnection

Class LazyConnection

src/12/storing_thread_specific_state/example2.py:4–20  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2import threading
3
4class 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
22def test(conn):
23 # Example use

Callers 1

example2.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected