List Comprehensions

Chris Angelico rosuav at gmail.com
Mon Dec 22 08:21:22 EST 2014


On Tue, Dec 23, 2014 at 12:07 AM, Roy Smith <roy at panix.com> wrote:
> def init_thread(opt):
>    opt['result'] = Queue.Queue()
>    thread = pause.Thread(opt)
>    thread.start()
>    return thread
>
> threads = [init_thread(opt) for opt in options]

If this is, indeed, just initializing the threads, then this might
make sense. Or alternatively, if you could subclass threading.Thread
and do all the work in __init__, then you could simply construct them
all:

class whatever(thread.Thread):
    def __init__(self, opt):
        self.queue = Queue.Queue()
        self.opt = opt
        super().__init__()
        self.start()

threads = [whatever(opt) for opt in options]

Just as long as you can come up with a sane name for the class, or the
initializer function, that makes sense without the list comp.

Incidentally, this is part of what I was saying about side effects
being okay in a list comp; either Roy's or my examples here would be a
list comp that has the side effect of starting a bunch of threads, and
I don't see it as being at all problematic. Just don't use a list comp
for _just_ the side effects.

ChrisA



More information about the Python-list mailing list