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

Class LazyConnection

src/12/storing_thread_specific_state/example1.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 if hasattr(self.local, 'sock'):
13 raise RuntimeError('Already connected')
14 self.local.sock = socket(self.family, self.type)
15 self.local.sock.connect(self.address)
16 return self.local.sock
17
18 def __exit__(self, exc_ty, exc_val, tb):
19 self.local.sock.close()
20 del self.local.sock
21
22def test(conn):
23 from functools import partial

Callers 1

example1.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected