From dd1b8dfe76feb0722988b1a51618c57a0f029437 Mon Sep 17 00:00:00 2001 From: Ayham970 <173636158+Ayham970@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:25:46 +0400 Subject: [PATCH] Correct the hidden-directory traversal example Assisted-by: OpenAI Codex --- newsfragments/+traversal-example.bugfix.rst | 1 + path/__init__.py | 22 ++++++++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) create mode 100644 newsfragments/+traversal-example.bugfix.rst diff --git a/newsfragments/+traversal-example.bugfix.rst b/newsfragments/+traversal-example.bugfix.rst new file mode 100644 index 0000000..d2ed1b0 --- /dev/null +++ b/newsfragments/+traversal-example.bugfix.rst @@ -0,0 +1 @@ +Correct the Traversal example to skip hidden directories by name and avoid traversing files. Make the example independent of the working directory's contents. diff --git a/path/__init__.py b/path/__init__.py index 731e88e..130b4e7 100644 --- a/path/__init__.py +++ b/path/__init__.py @@ -117,19 +117,31 @@ class Traversal: `follow` is a function that takes an item and returns True if that item should be followed and False otherwise. + It is called for files as well as directories, so it should + return False for files. For example, to avoid traversing into directories that begin with `.`: - >>> traverse = Traversal(lambda dir: not dir.startswith('.')) - >>> items = list(traverse(Path('.').walk())) + >>> traverse = Traversal( + ... lambda item: item.is_dir() and not item.name.startswith('.') + ... ) + >>> with TempDir() as root: + ... visible = (root / 'visible').mkdir() + ... hidden = (root / '.hidden').mkdir() + ... _ = (visible / 'keep.txt').touch() + ... _ = (hidden / 'skip.txt').touch() + ... with root: + ... items = list(traverse(Path('.').walk())) + ... sorted(str(item.name) for item in items) + ['.hidden', 'keep.txt', 'visible'] Directories beginning with `.` will appear in the results, but their children will not. - >>> dot_dir = next(item for item in items if item.is_dir() and item.startswith('.')) - >>> any(item.parent == dot_dir for item in items) - False + Check each item's :attr:`Path.name`, rather than the whole path, + so that a leading ``.`` in the starting path does not prevent + traversal of ordinary directories. """ def __init__(self, follow: Callable[[Path], bool]):