Skip to content

generator-never-iterated (EFF116)

Family: Execution Effects (EFF) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix

Opt-in: a call of a generator function whose generator nothing iterates (a statement, a value only tested for truth, a function handed to a thread, an atexit handler, or a filter predicate), so its body does not run.

Heuristic

This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs only when select or extend-select names its code or name. It has not been measured yet. See Rule Precision.

Experimental

The development corpus has few reports of it, and its premises are not yet certified. Experimental features can still change in behavior or precision, or be removed, in any release, and each change is listed in the release notes. An opt-in rule that is not experimental is stable and only off by default. See Experimental Features.

What it does

Checks for a call of a generator function whose generator nothing iterates. Calling a function with yield in its body (a def or an async def) only creates a generator: the body runs where the generator is iterated, step by step. A generator that is never iterated never runs its body, and nothing warns about it at run time.

It reports a call of a project generator function:

  • as a statement: self.load_rows(), cleanup(path);
  • whose value only a truth test reads: if gen():, while gen():, assert gen(), not gen(), bool(gen()). A generator is always true, so the test always passes (or never, under not), whatever the body would yield;
  • handed to a library call that calls it and drops what it returns, or tests it for truth: the calls of the ecosystem catalog's calls_unawaited table that EFF115 reads, such as threading.Thread(target=gen), threading.Timer(t, gen), multiprocessing.Process(target=gen), loop.call_soon(gen), atexit.register(gen), signal.signal(sig, gen), stack.callback(gen) of an exit stack, and the predicates of filter(gen, xs), itertools.filterfalse, itertools.takewhile, and itertools.dropwhile. The function is handed itself, as a bound method (self.drain), or through functools.partial.

Every function the call may run is a generator function without decorators other than staticmethod, classmethod, abstractmethod, override, or final: a call of a method that a subclass overrides with a plain function is no report. When the name is bound to more than one definition (def under if and else), the report says that the last one is a generator function.

It does not report:

  • a generator that is iterated, stepped, returned, yielded, stored, bound to a name, passed to any call, or delegated to (yield from gen());
  • a call that may run a plain function or a decorated one, such as another implementation of the method;
  • a generator function under any other decorator: contextlib.contextmanager, a test fixture, or a decorator heki does not know may call the function or wrap the generator;
  • a call heki does not resolve to a project function, and a library function that returns a generator;
  • a function handed to a library call that gives what it returns back to the caller: an executor's submit and map, the offloading APIs (asyncio.to_thread, loop.run_in_executor, ...), and weakref.finalize, whose object returns the result when it is called by hand;
  • an awaited call (await gen()), which raises TypeError, and which the type checkers report;
  • a generator expression: its scope is never called.

What a report states

A report states that the named function is a generator function, so the call only creates a generator, and that nothing iterates that generator: the body of the function does not run there.

Its premises:

  • Generator function: every function the call runs is a generator function that no decorator replaces, and the name of each is bound to one definition. Open when the name is bound to more than one definition (def under if and else).
  • Every implementation: the call's targets are every implementation it can run (R1, R2, R5). Open for a receiver typed by a protocol, a base class heki knows nothing of that may define the method, more than 64 classes to dispatch over, a member of a union that does not resolve, or a name the project binds to another object.
  • Never iterated: the generator is only the value of the call, with no name, and nothing reads it but a truth test; or the library call that runs the function drops what it returns or tests it for truth, as the catalog describes it (R3).

Not part of the claim: whether the body would have had an effect, and whether the caller meant the generator to run.

Why is this bad?

The work the function does never happens, and nothing fails: rows are never loaded into a cache the next line reads, a fallback behind if not gen(): never runs, a test helper with yield verifies nothing, a thread starts and ends at once. Adding a yield to a function (for a debug print, or to stream its results) silently breaks every caller that called it as a statement.

Example

import threading


class Code:
    def __init__(self, raw: list[bytes]) -> None:
        self.raw = raw
        self.cache: list[str] = []

    def load(self):
        for item in self.raw:
            self.cache.append(item.decode())
            yield self.cache[-1]

    def instruction(self, i: int) -> str:
        self.load()  # EFF116
        return self.cache[i]


def parse_extra(text: str):
    for line in text.splitlines():
        yield line.strip()


def check(text: str) -> None:
    if not parse_extra(text):  # EFF116
        print("nothing to parse")
    threading.Thread(target=parse_extra, args=(text,)).start()  # EFF116

Use instead:

class Code:
    def instruction(self, i: int) -> str:
        for _ in self.load():
            pass
        return self.cache[i]


def check(text: str) -> None:
    if not list(parse_extra(text)):
        print("nothing to parse")

Fix safety

No automatic fix.

Options

  • lint.extend-select = ["EFF116"] (or --extend-select EFF116) enables the rule. It is opt-in: selecting the EFF prefix does not enable it.

Known limitations

  • A generator bound to a name that nothing reads (rows = gen()) is not reported.
  • A truth test through a short-circuit expression whose value is used (gen() or default) is not reported: the expression's value is the generator.