python / python/cpython

Pathlib.iterdir semantics change dramatically under Python 3.13

Open
#129,871 11 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug report

Bug description:

This code behaves very differently on Python 3.13 than 3.12:

(p for p in pathlib.Path('does-not-exist').iterdir())
 🐚 py -3.12 -c "import pathlib; (p for p in pathlib.Path('does-not-exist').iterdir())"
 🐚 py -3.13 -c "import pathlib; (p for p in pathlib.Path('does-not-exist').iterdir())"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import pathlib; (p for p in pathlib.Path('does-not-exist').iterdir())
                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/opt/homebrew/Cellar/python@3.13/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/pathlib/_local.py", line 575, in iterdir
    with os.scandir(root_dir) as scandir_it:
         ~~~~~~~~~~^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'does-not-exist'

In Python 3.12, the generator expression was evaluated lazily, not invoking path.iterdir() until the generator was consumed. On 3.13, at least a portion of the generator is evaluated, triggering the exception when the dir does not exist.

I discovered this issue in https://github.com/jaraco/jaraco.develop/issues/26.

I looked at What's New for Python 3.13, and there's only one mention of generator expressions regarding mutation of locals in generator expressions, which doesn't seem to be relevant here.

That change mentions https://github.com/python/cpython/issues/74929, so maybe that change is also implicated in the change in execution order.

CPython versions tested on:

3.13

Operating systems tested on:

macOS

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

Reproduce the generator-expression behavior on Python 3.12 and 3.13, then inspect pathlib/_local.py around line 575 and the generator-expression semantics discussed in issue 74929. Determine whether the changed evaluation order is intentional or a regression, and add a focused regression test showing the expected timing of the FileNotFoundError.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.