2

I've been learning to program with Python on and off for a while now, and my current project is a download manager with a GUI written in wxPython. I have DownloadThreads, inheriting from threading.Thread, that I instantiate a varying amount of:

for i in xrange(self.thread_count):
    DownloadThread(self.queue, self.status, self.save_dir, i).start()

Because the number of threads I'm going to be creating isn't fixed, I can't assign the DownloadThread objects to variables, so I can't see how to access their methods, such as x.isAlive(). I thought about dynamically creating variables, but something about this seems like a really bad idea. How would I go about accessing these "anonymous" objects (terminology?), or am I going about this the wrong way? Thanks for reading, apologies if this is really simple / obvious.

1
  • To access an object you have to bind them, it's the same in every language I know. Anonymous things are for onetime use and throw away. Commented Apr 4, 2012 at 10:52

1 Answer 1

3

The simplest thing would be to keep all your threads in a list:

self.threads = []
for i in xrange(self.thread_count):
    self.threads.append(DownloadThread(self.queue, self.status, self.save_dir, i))
    self.threads[i].start()
Sign up to request clarification or add additional context in comments.

5 Comments

I don't really feel the list comprehension makes this clearer.
Thanks very much, this is the sort of thing I was after.
@Lattyware ok, used regular iteration syntax
@Lattyware I would probably factor the 'create a thread and start it' part into a separate function, and then use a list comprehension that calls the helper.
I generally see list comps as the clearest way to construct a list, but in this case, it's more an operation, with a list being made as a side-effect. It may just be me, but I prefer to keep this kind of thing in a regular loop - generally because I find it clearer and so I can add more code when needed. Of course, having it in a function in a list comp also allows for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.