Skip to content

fix: add __iter__ and __next__ to FileWrapper for PEP 3333 compliance#3550

Merged
benoitc merged 2 commits intobenoitc:masterfrom
r266-tech:fix/file-wrapper-iterable
Mar 24, 2026
Merged

fix: add __iter__ and __next__ to FileWrapper for PEP 3333 compliance#3550
benoitc merged 2 commits intobenoitc:masterfrom
r266-tech:fix/file-wrapper-iterable

Conversation

@r266-tech
Copy link
Copy Markdown
Contributor

Summary

Fixes #3396

The WSGI spec (PEP 3333) requires that wsgi.file_wrapper return an iterable object. Currently, Gunicorn's FileWrapper only implements __getitem__, which makes it iterable via old-style fallback but breaks code that explicitly relies on the iterator protocol (e.g., calling iter(), using next(), or passing to builtins expecting proper iterators).

Changes

  • Added __iter__ returning self
  • Added __next__ reading the next chunk and raising StopIteration when done
  • Added test in tests/test_http.py verifying the iterator protocol

Backward Compatibility

This is fully backward compatible:

  • Existing __getitem__-based iteration continues to work
  • for loops, list(), and other iteration patterns all work
  • The __next__ logic mirrors the existing __getitem__ logic exactly

The WSGI spec (PEP 3333) requires that wsgi.file_wrapper return an
iterable object. Gunicorn's FileWrapper only implemented __getitem__,
which technically makes it iterable via old-style iteration but breaks
code that explicitly relies on the iterator protocol (e.g., calling
iter() or using next()).

This adds __iter__ (returning self) and __next__ to make FileWrapper
a proper iterator, maintaining backward compatibility with existing
__getitem__-based usage.

Fixes benoitc#3396
@benoitc benoitc self-assigned this Mar 23, 2026
@benoitc benoitc merged commit f8fca7a into benoitc:master Mar 24, 2026
12 checks passed
@benoitc
Copy link
Copy Markdown
Owner

benoitc commented Mar 24, 2026

Thanks for the contribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FileWrapper should be iterable

3 participants