Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I had a similar problem and I must say Queue.Queue is quite good, however there is a missing piece of the puzzle. The following class helps deal with ensuring the object taken gets returned to the pool. Example is included.</p> <p>I've allowed 2 ways to use this class, with keyword or encapsulating object with destructor. The with keyword is preferred but if you can't / don't want to use it for some reason (most common is the need for multiple objects from multiple queues) at least you have an option. Standard disclaimers about destructor not being called apply if you choose to use that method.</p> <p>Hopes this helps someone with the same problem as the OP and myself.</p> <pre><code>class qObj(): _q = None o = None def __init__(self, dQ, autoGet = False): self._q = dQ if autoGet == True: self.o = self._q.get() def __enter__(self): if self.o == None: self.o = self._q.get() return self.o else: return self.o def __exit__(self, type, value, traceback): if self.o != None: self._q.put(self.o) self.o = None def __del__(self): if self.o != None: self._q.put(self.o) self.o = None if __name__ == "__main__": import Queue def testObj(Q): someObj = qObj(Q, True) print 'Inside func: {0}'.format(someObj.o) aQ = Queue.Queue() aQ.put("yam") with qObj(aQ) as obj: print "Inside with: {0}".format(obj) print 'Outside with: {0}'.format(aQ.get()) aQ.put("sam") testObj(aQ) print 'Outside func: {0}'.format(aQ.get()) ''' Expected Output: Inside with: yam Outside with: yam Inside func: sam Outside func: sam ''' </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload