[issue38789] difflib lacks a way to check if results are empty

Tim Peters report at bugs.python.org
Thu Nov 14 13:39:58 EST 2019


Tim Peters <tim at python.org> added the comment:

Please be explicit:  exactly which functions are you talking about, and exactly what do you want them to do instead.  Since, best I can tell, this is the first complaint of its kind, it's a pretty safe bet people can't guess what you want ;-)

Note that, e.g., Differ(...).compare(...) returns a generator-iterator.  There is no general way in Python to know whether a generator will yield a non-empty sequence of results without running the generator.  This is common to all generators, not unique to those difflib returns.

So, of course, the same kinds of idioms can be used as for any other generator.  For example:

foundone = False
for line in difflib.Differ(...).compare(...):
    if not foundone:
        # there is at least one result, and this is the first
        # maybe print a header line here, or whatever
        foundone = True
    process(line)
if not foundone:
    # the generator produced nothing

Simpler to code is to force the results into a list instead, but then you lose the possible memory-saving advantages of iterating over a generator:

    result = list(difflib.Differ(...).compare(...))
    if result:
        # there are results to deal with
    else:
        # the generator produced nothing

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38789>
_______________________________________


More information about the Python-bugs-list mailing list