[Python-ideas] BUG in standard while statement

Andrew Barnert abarnert at yahoo.com
Fri Sep 11 00:34:29 CEST 2015


On Sep 10, 2015, at 12:04, Chris Barker <chris.barker at noaa.gov> wrote:
> 
> However, I've found myself wanting a "make nothing comprehension". For some reason, I find myself frequently following a pattern where I want to call the same method on all the objects in a sequence:
> 
> for obj in a_sequence:
>     obj.a_method()
> 
> but I like the compactness of comprehensions, so I do:
> 
> [obj.a_method() for obj in a_sequence]

I think this is an anti-pattern. The point of a comprehension is that it's an expression, which gathers up results. You're trying to hide side effects inside an expression, which is a bad thing to do, and lamenting the fact that you get a useless value back, which of course you do because expressions have values, so that should be a sign that you don't actually want an expression here.

Also, compare the actual brevity here:

    [obj.a_method() for obj in a_sequence]
    for obj in a_sequence: obj.a_method()

You've replaced a colon with a pair of brackets, so it's actually less concise.

If you really want to do this anyway, you can use the consume recipe from the itertools docs or the more-itertools library or write your own one-liner:

    consume = partial(deque, maxlen=0)
    consume(obj.a_method() for obj in a_sequence)

At least this makes it explicit that you're creating and ignoring a bunch of values. But I still think it's much clearer to just use a for statement.



More information about the Python-ideas mailing list