pool.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """http://stackoverflow.com/questions/1514120/python-implementation-of-the-object-pool-design-pattern"""
  2. class QueueObject():
  3. def __init__(self, queue, auto_get=False):
  4. self._queue = queue
  5. self.object = self._queue.get() if auto_get else None
  6. def __enter__(self):
  7. if self.object is None:
  8. self.object = self._queue.get()
  9. return self.object
  10. def __exit__(self, Type, value, traceback):
  11. if self.object is not None:
  12. self._queue.put(self.object)
  13. self.object = None
  14. def __del__(self):
  15. if self.object is not None:
  16. self._queue.put(self.object)
  17. self.object = None
  18. def main():
  19. try:
  20. import queue
  21. except ImportError: # python 2.x compatibility
  22. import Queue as queue
  23. def test_object(queue):
  24. queue_object = QueueObject(queue, True)
  25. print('Inside func: {}'.format(queue_object.object))
  26. sample_queue = queue.Queue()
  27. sample_queue.put('yam')
  28. with QueueObject(sample_queue) as obj:
  29. print('Inside with: {}'.format(obj))
  30. print('Outside with: {}'.format(sample_queue.get()))
  31. sample_queue.put('sam')
  32. test_object(sample_queue)
  33. print('Outside func: {}'.format(sample_queue.get()))
  34. if not sample_queue.empty():
  35. print(sample_queue.get())
  36. if __name__ == '__main__':
  37. main()