python / python/cpython

os.scandir(): add option to yield the given path itself

Open
#99,454 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-feature
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

Feature or enhancement

I think it would be nice if os.scandir() had an option (that defaults to the current behaviour) which makes it also yield the root path itself as given by its path argument.

The benefit would be, that if one has code like e.g.:

def scandirtree(path):
    for p in os.scandir(path):
        if p.is_dir(follow_symlinks=False):
            yield p
            yield from scandirtree(p)
        else:
            yield p

one would also yield path and process that as well (in whatever one does with the generator).

It doesn't seem to be possible right now to write a warpper around scandir which would just yield path first, since one cannot create os.DirEntry objects (see #71983).

Pitch

The above in turn would be the familiar behaviour of many tools, e.g.

$ rm -rf path

also removes the path itself, not just its contents.

find path

also finds path itself.
Etc. pp.

So anyone who wants to implement a tool like these or similar behaviour, would no longer need to specially handle the path itself.

Previous discussion

https://discuss.python.org/t/os-scandir-should-have-an-option-to-also-yield-the-path-itself/18383

Thanks,
Chris.

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 the os.scandir() entry point and review the related limitation discussed in issue #71983 and the linked discussion. Define an opt-in behavior that preserves the current default while yielding the given path itself as a compatible result, then add coverage showing both behaviors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
operating-systems
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.