This rule raises an issue when a return statement with a value is used inside a generator function (a function that uses
yield).
When a generator function uses return with a value, the value is not sent to the caller like a normal function return. Instead, it is
silently attached to the StopIteration exception’s value attribute. Most callers iterate generators with a for
loop, which swallows StopIteration automatically and discards the returned value entirely. This makes the return value
effectively invisible and can lead to subtle bugs where developers expect the value to be accessible but it never reaches the calling code.
A bare return (without a value) in a generator is fine — it simply ends the generator’s execution early, similar to how
return works in a regular function.
def counter(n):
num = 0
while num < n:
yield num
num += 1
return num # Noncompliant: return with a value in a generator
def counter(n):
num = 0
while num < n:
yield num
num += 1
return # Compliant: bare return for early exit is fine
return in
generators