Skip to content

Commit 5e255eb

Browse files
author
Sakis Kasampalis
committed
Merge branch 'pep8_pool' of https://github.com/jcdenton/python-patterns into jcdenton-pep8_pool
2 parents 8469373 + 4e68e97 commit 5e255eb

File tree

1 file changed

+32
-35
lines changed

1 file changed

+32
-35
lines changed

pool.py

+32-35
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,51 @@
11
"""http://stackoverflow.com/questions/1514120/python-implementation-of-the-object-pool-design-pattern"""
22

33

4-
class qObj():
5-
_q = None
6-
o = None
7-
8-
def __init__(self, dQ, autoGet = False):
9-
self._q = dQ
10-
11-
if autoGet == True:
12-
self.o = self._q.get()
4+
class QueueObject():
5+
def __init__(self, queue, auto_get=False):
6+
self._queue = queue
7+
self.object = self._queue.get() if auto_get else None
138

149
def __enter__(self):
15-
if self.o == None:
16-
self.o = self._q.get()
17-
return self.o
10+
if self.object is None:
11+
self.object = self._queue.get()
12+
return self.object
1813

1914
def __exit__(self, type, value, traceback):
20-
if self.o != None:
21-
self._q.put(self.o)
22-
self.o = None
15+
if self.object is not None:
16+
self._queue.put(self.object)
17+
self.object = None
2318

2419
def __del__(self):
25-
if self.o != None:
26-
self._q.put(self.o)
27-
self.o = None
20+
if self.object is not None:
21+
self._queue.put(self.object)
22+
self.object = None
2823

2924

30-
if __name__ == "__main__":
25+
def main():
3126
try:
32-
import queue as Queue
33-
except: # python 2.x compatibility
34-
import Queue
27+
import queue
28+
except ImportError: # python 2.x compatibility
29+
import Queue as queue
3530

36-
def testObj(Q):
37-
someObj = qObj(Q, True)
38-
print('Inside func: {}'.format(someObj.o))
31+
def test_object(queue):
32+
queue_object = QueueObject(queue, True)
33+
print('Inside func: {}'.format(queue_object.object))
3934

40-
aQ = Queue.Queue()
41-
aQ.put("yam")
35+
sample_queue = queue.Queue()
4236

43-
with qObj(aQ) as obj:
44-
print("Inside with: {}".format(obj))
37+
sample_queue.put('yam')
38+
with QueueObject(sample_queue) as obj:
39+
print('Inside with: {}'.format(obj))
40+
print('Outside with: {}'.format(sample_queue.get()))
4541

46-
print('Outside with: {}'.format(aQ.get()))
42+
sample_queue.put('sam')
43+
test_object(sample_queue)
44+
print('Outside func: {}'.format(sample_queue.get()))
4745

48-
aQ.put("sam")
49-
testObj(aQ)
46+
if not sample_queue.empty():
47+
print(sample_queue.get())
5048

51-
print('Outside func: {}'.format(aQ.get()))
5249

53-
if not aQ.empty():
54-
print(aQ.get())
50+
if __name__ == '__main__':
51+
main()

0 commit comments

Comments
 (0)