3 ms·
Generators and generator expressions are useful every time your api involves an unbounded sequence. I once wrote a library of signal processing components base
by henrydark 4y ago
Generators and generator expressions are useful every time your api involves an unbounded sequence.
I once wrote a library of signal processing components based on the premise that the raw input signal is such a sequence, and its concrete type was Iterable[np.ndarray] (iterable of chunks of audio signal). Since the signal is unbounded - we just continue sampling from, say, a microphone forever - the types can't involve finite sequences like lists. A general iterable is works here, and then components that transform the sequence are themselves implemented as generators, or if they are very simple, as generator expressions.
Consider the following function for amplifying a signal:
def amplify(signal: Iterable[np.ndarray], a: float):
return (a*chunk for chunk in signal)
You can flip the whole infinite streams interface and talk about "pushing" chunks around, and it's an esthetic choice.