python / python/cpython

pathlib: Path.iterdir() is surprisingly not streaming

Open
#136,059 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib topic-pathlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Suprisingly (contrary to its name and being a generator), Path.iterdir() does not stream directory entries:

It reads all directory entries into memory before yielding the first entry.

This can cause excessive memory usage when "iterating" over very large directories.

Users would expect by default that .iterdir() operates in a streaming way, like UNIX find or readdir(), streaming e.g. the results of the underlying system calls such as getdents64() on Linux.

But it does entries = list(scandir_it) instead:

https://github.com/python/cpython/blob/c419af9e277bea7dd78f4defefc752fe93b0b8ec/Lib/pathlib/__init__.py#L835-L843

This should be documented, and can hopefully be fixed without too much breakage.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Related issues

Linked PRs
  • gh-136060

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with Lib/pathlib/init.py at the linked Path.iterdir() implementation around lines 835-843, then review related issue 129871 and linked PR 136060. Confirm the intended iteration behavior and compatibility expectations; done means the issue's streaming behavior is addressed and covered by the relevant pathlib tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
operating-systems
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.