Temporary variables in list comprehensions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jan 8 23:49:10 EST 2017


On Monday 09 January 2017 15:09, Chris Angelico wrote:

> On Mon, Jan 9, 2017 at 2:53 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> [(tmp, tmp + 1) for x in data for tmp in [expensive_calculation(x)]]
>>
>>
>> I can't decide whether that's an awesome trick or a horrible hack...
> 
> A horrible hack on par with abusing a recursive function's arguments
> for private variables. 

What's wrong with that? That's a perfectly legitimate technique. I prefer to 
hide it behind a private function rather than expose it in a public interface:

# instead of this
def recursive(arg, _internal=None):
    """Recursive function. Don't supply the _internal argument."""
    ...
    return recursive(arg-1, spam)


# I usually prefer this
def recursive(arg):
    """Recursive function."""
    return _recursive(arg, spam)

def _recursive(arg, internal):
    ...


but that's just polishing the code.



> Much better would be to refactor the append
> part:
> 
> def this_and_one(value):
>     return value, value + 1

I wouldn't call that "much better". Requiring an extra function defeats the 
purpose of using a list comp, and it doesn't scale well for multiple list comps 
each of which needs a different helper function:


def this_and_one(value):
    return value, value + 1

def this_less_one_and_this_plus_one_and_this(value):
    return value - 1, value + 1, value

def this_and_that_or_something(value):
    return value, value.that() or something

def extract_value(value):
    return spam[value] or ham[value] or eggs[value]


and so on. Helper functions are good. Helper functions that are only used 
*once* are a code smell. *LOTS* of helper functions that are only used once are 
a sign that something is horrible, and it might just be your language...



-- 
Steven
"Ever since I learned about confirmation bias, I've been seeing 
it everywhere." - Jon Ronson



More information about the Python-list mailing list