forked from faif/python-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.py
More file actions
Latest commit
61 lines (44 loc) · 1.49 KB
/
Copy pathpool.py
File metadata and controls
61 lines (44 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""http://stackoverflow.com/questions/1514120/python-implementation-of-the-object-pool-design-pattern"""
classQueueObject():
def__init__(self, queue, auto_get=False):
self._queue=queue
self.object=self._queue.get() ifauto_getelseNone
def__enter__(self):
ifself.objectisNone:
self.object=self._queue.get()
returnself.object
def__exit__(self, Type, value, traceback):
ifself.objectisnotNone:
self._queue.put(self.object)
self.object=None
def__del__(self):
ifself.objectisnotNone:
self._queue.put(self.object)
self.object=None
defmain():
try:
importqueue
exceptImportError: # python 2.x compatibility
importQueueasqueue
deftest_object(queue):
queue_object=QueueObject(queue, True)
print('Inside func: {}'.format(queue_object.object))
sample_queue=queue.Queue()
sample_queue.put('yam')
withQueueObject(sample_queue) asobj:
print('Inside with: {}'.format(obj))
print('Outside with: {}'.format(sample_queue.get()))
sample_queue.put('sam')
test_object(sample_queue)
print('Outside func: {}'.format(sample_queue.get()))
ifnotsample_queue.empty():
print(sample_queue.get())
if__name__=='__main__':
main()
### OUTPUT ###
# Inside with: yam
# Outside with: yam
# Inside func: sam
# Outside func: sam