Search Queue

Tim Golden tjgolden at gmail.com
Tue Jan 16 10:51:16 EST 2007


abcd wrote:
> I have a class such as...

[... ]

> And I am storing them in a Queue.Queue...
>
> import Queue
> q = Queue.Queue()
> q.put(Foo('blah'))
> q.put(Foo('hello world'))
> q.put(Foo('test'))
>
> how can I search "q" for an instance of Foo which has 'id' equal to say
> 2?  Typically a queue only lets you put and get, not really search.

It's possible you're seeing the Queue structure as
some sort of list / array, rather than its intended purpose
as a thread-safe channel. If I'm wrong, ignore the rest of
this post. If, however, you're just after a container for
various instances of Foo then use a list or a dict,
depending on what you're after.

eg,

<code>
class Foo:
  def __init__ (self, id):
    self.id = id

list_of_foos = [Foo('blah'), Foo('hello'), Foo('test')]
dict_of_foos = dict ((f.id, f) for f in list_of_foos)

print dict_of_foos['blah']

</code>

TJG




More information about the Python-list mailing list