Skip to content

Improve performance of os.walk() #119169

Description

@barneygale

There are a couple of minor performance improvements possible in os.walk():

  • We don't need to manually pump the os.scandir iterator, given we handle exceptions from next() like exceptions from scandir() itself, i.e. by ignoring the problematic directory and moving on. We can use a for loop like filthy casuals.
  • In bottom-up mode, we can handle exceptions from entry.is_symlink() in the same block as those from entry.is_dir(), which avoids a few temporary variables.
  • In top-down mode, we can call os.path.join() once on a parent directory rather than for each child path.

Linked PRs

Activity

  1. barneygale commented on May 19, 2024

    @barneygale
    ContributorAuthor

    In bottom-up mode, we can handle exceptions from entry.is_symlink() in the same block as those from entry.is_dir(), which avoids a few temporary variables.

    Upon closer inspection, I think I was wrong. Symlinks to directories where is_symlink() raises should still be categorised as dirs.

  2. added 5 commits that reference this issue on May 19, 2024
  3. added a commit that references this issue on May 29, 2024
  4. added a commit that references this issue on May 29, 2024
  5. added 2 commits that reference this issue on Jul 6, 2024
  6. serhiy-storchaka commented on Jul 8, 2024

    @serhiy-storchaka
    Member

    There are too many open PRs. Are they independent? Alternative? What should I review?

  7. added a commit that references this issue on Jul 8, 2024
  8. barneygale commented on Jul 8, 2024

    @barneygale
    ContributorAuthor

    There are too many open PRs. Are they independent? Alternative? What should I review?

    The two draft PRs (GH-121433 and GH-119186) depend on GH-119473. The three non-draft PRs are independent and can be reviewed/accepted/rejected in any order or combination.

  9. added 2 commits that reference this issue on Jul 11, 2024
  10. added 2 commits that reference this issue on Jul 17, 2024
  11. added a commit that references this issue on Sep 3, 2025
  12. added a commit that references this issue on Sep 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usage

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions