Why does itertools have recipes?

I’m not really sure if this is the right place to ask this, but I’m kind of confused about why the itertools module has recipes like grouper and sliding_window in the documentation, rather than in the module itself.

I know that the itertools module itself is written in C for performance reasons, and the recipes are written in pure-Python but make use of code written in C (e.g. grouper calls zip_longest) so they’re presumably “fast enough” without needing to be written in C, but I’m not asking “why aren’t they implemented in C”.

There could be, say, a itertools.recipes submodule of pure Python code which contains those recipes, and that would, at least at first glance, seem to make more sense than including them in the module documentation and making people copy-paste them when they need them.

But, I suspect that if such an obvious option wasn’t taken that there’s a reason for it. So, what is the reason that the recipes are provided via the documentation?

Also, as a follow-up question, are there any other modules in the stdlib that do something similar?

Searching site:docs.python.org recipes finds for example:

I guess the recipes are considered only examples that might need some adjustment for each use, not fully finalized generic library code?

1 Like

Once you add something to the stdlib, changing the implementation (even fixing bugs) becomes much more tedious, and sometimes even close to impossible. Breaking changes need deprecation warnings for a minimum of two release cycles before the problematic behaviour can change (see PEP 387). Other times, one need to add a new API and keep the old, malfunctioning API. Using recipes is very lightweight; adding, removing, or modifying recipes are simply doc updates that can easily be backported to all bugfix branches.

3 Likes

more-itertools has all the itertools recipes btw, and more, so you can use that instead of copy pasting recipes from the itertools docs

https://more-itertools.readthedocs.io/

1 Like