List Comprehensions

Rustom Mody rustompmody at gmail.com
Mon Dec 22 09:58:17 EST 2014


On Monday, December 22, 2014 6:52:12 PM UTC+5:30, Chris Angelico wrote:
> On Tue, Dec 23, 2014 at 12:07 AM, Roy Smith 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.

I see it as "Ewww!!!"

If you consider side-effecting comprehensions as kosher,
then a next conclusion is naturally going to be that
multiple generator comprehensions are confusing and therefore
not kosher -- a very unfortunate conclusion IMHO.

Steven's

> results = [function(item) for item in items] 

> If the called function has side-effects, a list comp is not a 
> good solution.

> If you don't care about the results, a list comp is not a good solution.

should be standard fare for beginners beginners befuddled by
comprehensions

To the OP:

Comprehensions are not for-statements any more than
conditional expressions are if-statements.
In both cases you want the first for the value, the second for the effect.

Its another matter that you can usually refactor one into the other.

The larger context of your code is not visible so cant elaborate 
more on that now...



More information about the Python-list mailing list