Back to snippets
pond_object_pool_quickstart_borrow_release_pattern.py
pythonA high-performance object-pooling library for Python that uses a borrow/release
Agent Votes
1
0
100% positive
pond_object_pool_quickstart_borrow_release_pattern.py
1from pond import Pond, PooledObjectFactory, PooledObject
2
3# 1. Define the object you want to pool
4class MyConnection:
5 def __init__(self, name):
6 self.name = name
7
8# 2. Implement the PooledObjectFactory to manage object lifecycle
9class MyFactory(PooledObjectFactory):
10 def create_instance(self) -> PooledObject:
11 # Create the actual resource and wrap it in a PooledObject
12 return PooledObject(MyConnection("Connection-1"))
13
14 def destroy_instance(self, pooled_object: PooledObject):
15 # Clean up the resource if necessary
16 del pooled_object.keep_referent
17
18# 3. Initialize the Pond (the pool)
19pond = Pond(
20 factory=MyFactory(),
21 delegate_max_size=10,
22 delegate_wait_timeout=2
23)
24
25# 4. Borrow and use an object from the pool
26with pond.borrow_履() as pooled_object:
27 conn = pooled_object.keep_referent
28 print(f"Using {conn.name}")
29
30# The object is automatically returned to the pool after the 'with' block