Skip to content

Instantly share code, notes, and snippets.

@rwperrott
Created August 24, 2024 12:40
Show Gist options
  • Save rwperrott/2a72529fc8c83762d9e649c881798c20 to your computer and use it in GitHub Desktop.
Save rwperrott/2a72529fc8c83762d9e649c881798c20 to your computer and use it in GitHub Desktop.
An adaption of my "with" statement support, in my typed adapting classes for Pond, to plain Pond classes.
from contextlib import contextmanager
from typing import Optional, Generator, Any
from pond import Pond, PooledObjectFactory, PooledObject
@contextmanager
def skim(pond: Pond,
factory: Optional[PooledObjectFactory] = None,
name: Optional[str] = None
) -> Generator[Any, Any, None]:
"""Enables simpler borrowed use of a pooled object, via a `with` statement.
Sadly, I could not use generics TypeVar to persuade the "as" value to become a typed value,
so I had to copy the "as" variable value into a type hinted variable, for typed use.
Maybe someone else can figure this out.
"""
po = pond.borrow(factory, name)
try:
yield po.use()
finally:
pond.recycle(po, factory, name)
def test_skim():
class ListPOF(PooledObjectFactory):
def createInstance(self) -> PooledObject:
return PooledObject(list())
def validate(self, po: PooledObject) -> bool:
return True
def reset(self, po: PooledObject, **kwargs: Any) -> PooledObject:
k: list = po.keeped_object
k.clear()
return po
def destroy(self, po: PooledObject) -> None:
pass
pond = Pond()
factory = ListPOF()
name = factory.factory_name()
pond.register(factory)
print("\n")
with skim(pond, factory=factory) as ko:
l1: list[str] = ko
l1.append('1')
l1.append('2')
l1.append('3')
print("Test 1,2,3: " + ",".join(l1) + "\n")
with skim(pond, name=name) as ko:
l2: list[str] = ko
l2.append('4')
l2.append('5')
l2.append('6')
print("Test 4,5,6: " + ",".join(l2) + "\n")
with skim(pond, factory=factory, name=name) as ko:
l3: list[str] = ko
l3.append('7')
l3.append('8')
l3.append('9')
print("Test 7,8,9: " + ",".join(l3) + "\n")
test_skim()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment