[Python-ideas] Assignments in list/generator expressions

Nick Coghlan ncoghlan at gmail.com
Tue Apr 12 07:47:22 CEST 2011


On Tue, Apr 12, 2011 at 3:06 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> ys = [y for x in xs given f(x) if p(x) else g(x) as y]

You know, I may have spoken too soon in saying PEP 3150 couldn't help
with the list comprehension use case.

def remember(f):
    """Decorator that remembers result until arguments change"""
    # Essentially an LRU cache for exactly 1 entry
    last_args = object(), object()
    last_result = None
    @functools.wraps(f)
    def wrapped(*args, **kwds):
        nonlocal last_args, last_result
        if last_args != args, kwds:
            last_args = args, kwds
            last_value = f(*args, **kwds)
        return last_value
    return wrapped

ys = [y(x) for x in xs if y(x)] given:
    y = remember(f)

Or for the more complicated case:

ys = [y(x) for x in xs if y(x)] given:
    @remember
    def y(x):
        fx  = f(x)
        return fx if fx else g(x)

Or even (using the subgenerator approach):

ys = [y for y in all_y if y] given:
    all_y = (f(x) for x in x)

There are all *sorts* of tricks that open up once you don't even need
to think about possible impacts on the local namespace.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list