[issue18652] Add itertools.coalesce

Nick Coghlan report at bugs.python.org
Sun Aug 4 14:09:45 CEST 2013


Nick Coghlan added the comment:

(Updated the issue title to reflect the currently proposed name and location for the functionality)

While I'm a fan of explicit iteration as well ("inside every reduce is a loop trying to get out"), I think the fact Martin's explicit loop is buggy (it will never match re2 as it always bails on the first iteration) helps make the case for coalesce. The correct explicit loop looks something like this:

    for r in (re1, re2):
        m = r.match('abc')
        if m is None:
            continue
        if r is re1:
            print('re1', m.group(1))
        elif r is re2:
            print('re1', m.group(1))
        break # Matched something
    else:
        print('No match')

(Or the equivalent that indents the loop body further and avoids the continue statement)

The coalesce version has a definite advantage in not needing a loop else clause to handle the "nothing matched" case:

    m = coalesce(regexp.match('abc') for regexp in [re1, re2])
    if m is None:
        print('no match!')
    elif m.re is re1:
        print('re1', m.group(1))
    elif m.re is re2:
        print('re2', m.group(1))

----------
title: Add a “first”-like function to the stdlib -> Add itertools.coalesce

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue18652>
_______________________________________


More information about the Python-bugs-list mailing list